target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
import re
def swap_language_greeting(s):
if re.match(r'^Hello\b', s):
return re.sub(r'^Hello\b', 'Hi', s)
elif re.match(r'^Hola\b', s):
return re.sub(r'^Hola\b', 'Buenos días', s)
elif re.match(r'^Bonjour\b', s):
return re.sub(r'^Bonjour\b', 'Salut', s)
else:
return s | simplelr_Apps | [
{
"content": "Question:\nCreate a method `swap_language_greeting` that takes a string which is a sentence with a greeting in one of the following languages: English, Spanish, or French. The method should swap the greeting in those languages to a different greeting in the same language, cycling through in a pred... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7700,
"level": 1,
"question": "Create a method `swap_language_greeting` that takes a string which is a sentence with a greeting in one of the following languages: English, Spanish, or French. The method should swap the greeting in those languages to a different greeting in the same ... |
def binomial_coefficient(n, k):
if k < 0 or k > n:
return 0
if k == 0 or k == n:
return 1
k = min(k, n - k)
result = 1
for i in range(1, k + 1):
result = result * (n - k + i) // i
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the number of ways to choose `k` items from `n` items without repetition and without order. This is known as the binomial coefficient, often denoted as \\( C(n, k) \\) or \\( \\binom{n}{k} \\).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7701,
"level": 1,
"question": "Write a function to calculate the number of ways to choose `k` items from `n` items without repetition and without order. This is known as the binomial coefficient, often denoted as \\( C(n, k) \\) or \\( \\binom{n}{k} \\).",
"split": "train"
} |
import math
from typing import List
def find_primes_up_to(n: int) -> List[int]:
"""
Find all prime numbers up to a specified number using the Sieve of Eratosthenes algorithm.
Args:
- n (int): The upper limit to find primes, inclusive.
Returns:
- List[int]: A list of all prime numbers ... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Objective\nImplement a function to find all prime numbers up to a given number using the Sieve of Eratosthenes algorithm.\n\n#### Problem Statement\nA prime number is a natural number greater than 1 that is not a product of two smaller natural numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7702,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Objective\nImplement a function to find all prime numbers up to a given number using the Sieve of Eratosthenes algorithm.\n\n#### Problem Statement\nA prime number is a natural number greater than 1 that is not a ... |
def list_of_tuples_to_dict(tuple_list):
return dict(tuple_list) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of tuples as input, where each tuple contains a string and a number. The function should return a dictionary where the strings are the keys and the numbers are the values. For example, given the list `[('apple', 1), ('banana', 2)]`, the functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7703,
"level": 1,
"question": "Create a Python function that takes a list of tuples as input, where each tuple contains a string and a number. The function should return a dictionary where the strings are the keys and the numbers are the values. For example, given the list `[('apple... |
import math
def min_candies(a, b):
gcd = math.gcd(a, b)
lcm = (a * b) // gcd
return lcm
| simplelr_Taco | [
{
"content": "Question:\n# Problem\n\nIn a small village, there is a unique custom of distributing candies among children. The village chief has a particular way of determining how many candies each child receives. The total number of candies to be distributed, `t`, must be an integer divisible by two specific ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7704,
"level": 1,
"question": "# Problem\n\nIn a small village, there is a unique custom of distributing candies among children. The village chief has a particular way of determining how many candies each child receives. The total number of candies to be distributed, `t`, must be an... |
def custom_sum_or_difference(A, B):
if A > B:
return A - B
else:
return A + B | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two numbers as input, A and B, and returns their sum. However, if A is greater than B, the function should return the absolute difference between A and B instead.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7705,
"level": 1,
"question": "Create a function that takes two numbers as input, A and B, and returns their sum. However, if A is greater than B, the function should return the absolute difference between A and B instead.",
"split": "train"
} |
def longest_non_decreasing_subsequence(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[j] <= nums[i]:
if dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
return max(dp) | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet that can find the maximum number of elements in a list that can be combined to make a non-decreasing sequence? For example, given a list [5, 3, 4, 8, 6, 7], the longest non-decreasing subsequence would be [3, 4, 6, 7] or [3, 4, 8], both of which hav... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7706,
"level": 1,
"question": "Can you provide a Python code snippet that can find the maximum number of elements in a list that can be combined to make a non-decreasing sequence? For example, given a list [5, 3, 4, 8, 6, 7], the longest non-decreasing subsequence would be [3, 4, 6,... |
def is_valid_password(s):
if len(s) < 8:
return False
has_upper = any(c.isupper() for c in s)
has_lower = any(c.islower() for c in s)
has_digit = any(c.isdigit() for c in s)
special_chars = "!@#$%^&*()-+"
has_special = any(c in special_chars for c in s)
return has_upper and has_lower... | simplelr_Taco | [
{
"content": "Question:\nAlice is designing a password validation system for her new application. The password must meet the following criteria to be considered valid:\n- It must be at least 8 characters long.\n- It must contain at least one uppercase letter.\n- It must contain at least one lowercase letter.\n-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7707,
"level": 1,
"question": "Alice is designing a password validation system for her new application. The password must meet the following criteria to be considered valid:\n- It must be at least 8 characters long.\n- It must contain at least one uppercase letter.\n- It must contai... |
from collections import Counter
def most_common_triplet(s):
triplets = [s[i:i+3] for i in range(len(s) - 2)]
counts = Counter(triplets)
most_common = counts.most_common(1)
return (most_common[0][0], most_common[0][1]) | simplelr_Package | [
{
"content": "Question:\nDesign and Output:\n\nYou are required to implement a function that identifies the most common sequence of three consecutive characters in a given string. The function should return the most frequent triplet and the number of times it appears. If there are multiple triplets with the hig... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7708,
"level": 1,
"question": "Design and Output:\n\nYou are required to implement a function that identifies the most common sequence of three consecutive characters in a given string. The function should return the most frequent triplet and the number of times it appears. If there... |
def findSmallestMissingPositive(arr):
positives = set()
for num in arr:
if num > 0:
positives.add(num)
if not positives:
return 1
current = 1
while current in positives:
current += 1
return current
| simplelr_Taco | [
{
"content": "Question:\nYou are given an unsorted list of integers and your task is to find the smallest missing positive integer from the list. Implement a function `findSmallestMissingPositive()` that takes a list of integers as input and returns the smallest missing positive integer.\n\nExample:\nInput:\n[-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7709,
"level": 1,
"question": "You are given an unsorted list of integers and your task is to find the smallest missing positive integer from the list. Implement a function `findSmallestMissingPositive()` that takes a list of integers as input and returns the smallest missing positi... |
import heapq
from typing import List
def dijkstra_shortest_paths(city: List[List[int]], start: int) -> List[int]:
n = len(city)
# Initialize distances to infinity except the start node
dist = [float('inf')] * n
dist[start] = 0
# Priority queue stores tuples of (distance, node)
heap = []
hea... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou are tasked with developing a navigation system that computes the shortest path from a starting point to various destinations within a city. You will simulate this by implementing Dijkstra's algorithm on a graph representing the city's intersections (vertices) and road... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7710,
"level": 1,
"question": "#### Scenario\nYou are tasked with developing a navigation system that computes the shortest path from a starting point to various destinations within a city. You will simulate this by implementing Dijkstra's algorithm on a graph representing the city'... |
def are_isomorphic(str1: str, str2: str) -> bool:
if len(str1) != len(str2):
raise ValueError("Strings are of different lengths, cannot be isomorphic")
mapping_str1 = {}
mapping_str2 = {}
for c1, c2 in zip(str1, str2):
# Check mapping from str1 to str2
if c1 in mapping_... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context\nIn computer science, an isomorphism between two strings means you can map the characters of one string to characters of another string one-to-one and onto. This means no two characters of the first string map to the same character of the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7711,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context\nIn computer science, an isomorphism between two strings means you can map the characters of one string to characters of another string one-to-one and onto. This means no two characters of the first string... |
def returnsToOrigin(moves):
x = 0
y = 0
for move in moves:
if move == 'U':
y += 1
elif move == 'D':
y -= 1
elif move == 'R':
x += 1
elif move == 'L':
x -= 1
return x == 0 and y == 0
| simplelr_Taco | [
{
"content": "Question:\nA robot on a grid starts at position $(0, 0)$ and can receive a sequence of moves that impact its position on the grid. The possible moves are 'U' (which moves the robot up by 1 unit), 'D' (which moves the robot down by 1 unit), 'L' (which moves the robot left by 1 unit), and 'R' (which... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7712,
"level": 1,
"question": "A robot on a grid starts at position $(0, 0)$ and can receive a sequence of moves that impact its position on the grid. The possible moves are 'U' (which moves the robot up by 1 unit), 'D' (which moves the robot down by 1 unit), 'L' (which moves the ro... |
def reverse_string(s):
return s[::-1] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns a new string with the characters reversed.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7713,
"level": 1,
"question": "Write a Python function that takes a string as input and returns a new string with the characters reversed.",
"split": "train"
} |
def generate_time_points(total_hours, step_size, to_minutes=False, validate_output=False):
"""
Generates a list of time points from 0 to total_hours with a specified step size.
The time points can be converted to minutes if required. The output can be validated.
Args:
total_hours (float): The t... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that generates a list of time points starting from 0 to a given number of hours, with a specific step size, and rounds the times to the second decimal place. The function should also be able to handle conversion from hours to minutes if required. Ensure to inclu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7714,
"level": 1,
"question": "Create a Python function that generates a list of time points starting from 0 to a given number of hours, with a specific step size, and rounds the times to the second decimal place. The function should also be able to handle conversion from hours to m... |
import torch
import torch.nn.functional as F
def custom_conv_block(input_tensor, out_channels, kernel_size, stride, padding, pool_size, dropout_rate):
"""
Implements a custom convolutional block.
Arguments:
input_tensor (torch.Tensor): The input tensor with shape (batch_size, in_channels, height, widt... | simplelr_Docs | [
{
"content": "Question:\nImplementing a Custom Convolutional Block in PyTorch\n\n#### Introduction:\nYou are tasked with implementing a custom convolutional block using PyTorch's `torch.nn.functional` module. This block will be a critical component of a convolutional neural network (CNN) for image classificatio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7715,
"level": 1,
"question": "Implementing a Custom Convolutional Block in PyTorch\n\n#### Introduction:\nYou are tasked with implementing a custom convolutional block using PyTorch's `torch.nn.functional` module. This block will be a critical component of a convolutional neural ne... |
def longest_balanced_substring(s):
balance_map = {0: -1}
balance = 0
max_len = 0
for i, c in enumerate(s):
if c == '1':
balance += 1
else:
balance -= 1
if balance in balance_map:
current_length = i - balance_map[balance]
if current_... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a binary string `s` which contains only the characters '0' and '1'. A substring of `s` is called balanced if the number of '0's and the number of '1's in the substring are equal. Write a function that returns the length of the longest balanced substring in `s`. If there is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7716,
"level": 1,
"question": "You are given a binary string `s` which contains only the characters '0' and '1'. A substring of `s` is called balanced if the number of '0's and the number of '1's in the substring are equal. Write a function that returns the length of the longest bal... |
def custom_merge(list1, list2):
merged = []
for a, b in zip(list1, list2):
merged.append(a + b)
if len(list1) > len(list2):
merged.extend(list1[len(list2):])
elif len(list2) > len(list1):
merged.extend(list2[len(list1):])
return merged | simplelr_Filter | [
{
"content": "Question:\nHow can I create a custom merge function for merging two lists of strings in Python, where the merge function should concatenate strings at matching indices and append unmatched strings from either list to the result?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7717,
"level": 1,
"question": "How can I create a custom merge function for merging two lists of strings in Python, where the merge function should concatenate strings at matching indices and append unmatched strings from either list to the result?",
"split": "train"
} |
def are_anagrams(str1, str2):
if len(str1) != len(str2):
return False
return sorted(str1) == sorted(str2) | simplelr_Apps | [
{
"content": "Question:\n### What's an Anagram Checker?\n\nAn anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word `\"listen\"` can be rearranged to form `\"silent\"`.\n\n### Task:\n\nYour job is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7718,
"level": 1,
"question": "### What's an Anagram Checker?\n\nAn anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word `\"listen\"` can be rearranged to form `\"sil... |
def min_path_sum(grid):
if not grid or not grid[0]:
return 0
rows = len(grid)
cols = len(grid[0])
dp = [[0] * cols for _ in range(rows)]
dp[0][0] = grid[0][0]
# Fill the first row
for j in range(1, cols):
dp[0][j] = dp[0][j-1] + grid[0][j]
# Fill the first colum... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the minimum path sum in a 2D grid.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7719,
"level": 1,
"question": "Write a function to find the minimum path sum in a 2D grid.",
"split": "train"
} |
def swap_case(s):
result = []
for c in s:
if c.islower():
result.append(c.upper())
elif c.isupper():
result.append(c.lower())
else:
result.append(c)
return ''.join(result) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and changes all the letters to their opposite case.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7720,
"level": 1,
"question": "Create a function that takes a string as input and changes all the letters to their opposite case.",
"split": "train"
} |
def is_palindrome(s):
cleaned = ''.join([c.lower() for c in s if c.isalnum()])
return cleaned == cleaned[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given string `s` is a palindrome. A palindrome is a string that reads the same backward as forward. The function should return `True` if the string is a palindrome, and `False` otherwise. You should consider only alphanumeric characters and ignore cases.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7721,
"level": 1,
"question": "Write a function to check if a given string `s` is a palindrome. A palindrome is a string that reads the same backward as forward. The function should return `True` if the string is a palindrome, and `False` otherwise. You should consider only alphanum... |
def shift_string(s: str, k: int) -> str:
result = []
for c in s:
pos = ord(c) - ord('a')
new_pos = (pos + k) % 26
new_char = chr(new_pos + ord('a'))
result.append(new_char)
return ''.join(result) | simplelr_Apps | [
{
"content": "Question:\nImplement a function that takes a string consisting of lowercase letters and an integer `k` as input. The function should return a new string where each character has been 'shifted' k positions forward in the alphabet. For example, with `k = 3`, 'a' becomes 'd', 'b' becomes 'e', ..., an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7722,
"level": 1,
"question": "Implement a function that takes a string consisting of lowercase letters and an integer `k` as input. The function should return a new string where each character has been 'shifted' k positions forward in the alphabet. For example, with `k = 3`, 'a' be... |
def dayOfWeek(day: int) -> str:
days = {1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday",
5: "Friday", 6: "Saturday", 7: "Sunday"}
return days.get(day, "Invalid day") | simplelr_Filter | [
{
"content": "Question:\nWrite the function dayOfWeek (day: int) that takes an integer representing a day of the week and returns its corresponding name as a string. The function should handle values from 1 to 7, where 1 corresponds to Monday and 7 to Sunday. For any other input, the function should return \"In... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7723,
"level": 1,
"question": "Write the function dayOfWeek (day: int) that takes an integer representing a day of the week and returns its corresponding name as a string. The function should handle values from 1 to 7, where 1 corresponds to Monday and 7 to Sunday. For any other inp... |
def contain_string(haystack: str, needle: str) -> int:
return haystack.find(needle) | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with implementing a function to find the first occurrence of a string (`needle`) inside another string (`haystack`). This task tests your understanding of string searching algorithms and requires careful handling of edge cases and performance considerations.\n\n#### Funct... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7724,
"level": 1,
"question": "You are tasked with implementing a function to find the first occurrence of a string (`needle`) inside another string (`haystack`). This task tests your understanding of string searching algorithms and requires careful handling of edge cases and perfor... |
def removeOddsAndSort(lst):
even_list = [x for x in lst if x % 2 == 0]
even_list.sort()
return even_list
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, remove all odd elements from the list and return the modified list in sorted order.\n\nExample 1:\nInput:\nlst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]\nOutput: [2, 4, 6]\nExplanation: The odd elements [3, 1, 5, 9, 5, 3, 5] are removed and the remaining even element... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7725,
"level": 1,
"question": "Given a list of integers, remove all odd elements from the list and return the modified list in sorted order.\n\nExample 1:\nInput:\nlst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]\nOutput: [2, 4, 6]\nExplanation: The odd elements [3, 1, 5, 9, 5, 3, 5] are rem... |
def is_subsequence(str1, str2):
if not str1:
return True
if len(str2) < len(str1):
return False
i = 0
for char in str2:
if char == str1[i]:
i += 1
if i == len(str1):
break
return i == len(str1) | simplelr_Filter | [
{
"content": "Question:\nI have two strings, `str1` and `str2`. I want to determine if `str1` is a subsequence of `str2`. Can you provide a Python function to check this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7726,
"level": 1,
"question": "I have two strings, `str1` and `str2`. I want to determine if `str1` is a subsequence of `str2`. Can you provide a Python function to check this?",
"split": "train"
} |
def flatten(nested_list):
result = []
for item in nested_list:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
| simplelr_Taco | [
{
"content": "Question:\nImagine you are working with nested lists and you need to flatten them into a single list. However, you want to maintain a specific order of elements as they appear from left to right, traversing each sublist.\n\nA nested list could comprise other lists or single elements. Your task is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7727,
"level": 1,
"question": "Imagine you are working with nested lists and you need to flatten them into a single list. However, you want to maintain a specific order of elements as they appear from left to right, traversing each sublist.\n\nA nested list could comprise other list... |
def hex_to_rgb(hex_colors):
result = []
for color in hex_colors:
stripped = color[1:]
rr = stripped[0:2]
gg = stripped[2:4]
bb = stripped[4:6]
r = int(rr, 16)
g = int(gg, 16)
b = int(bb, 16)
result.append((r, g, b))
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that converts a list of hexadecimal color codes to their corresponding RGB values. The hexadecimal color codes are given as strings in the format '#RRGGBB', where RR, GG, and BB are two-digit hexadecimal numbers representing the red, green, and blue components of... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7728,
"level": 1,
"question": "Write a Python function that converts a list of hexadecimal color codes to their corresponding RGB values. The hexadecimal color codes are given as strings in the format '#RRGGBB', where RR, GG, and BB are two-digit hexadecimal numbers representing the... |
def compress_string(s):
if not s:
return ""
current_char = s[0]
count = 1
result = []
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(f"{current_char}{count}")
current_char = char
count = 1
result.... | simplelr_Taco | [
{
"content": "Question:\nWrite a function `compressString`/`compress_string` that takes a string as input and returns a new string where consecutive occurrences of the same character are replaced with that character followed by the count of duplicates. If the run length is 1, just add the character without the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7729,
"level": 1,
"question": "Write a function `compressString`/`compress_string` that takes a string as input and returns a new string where consecutive occurrences of the same character are replaced with that character followed by the count of duplicates. If the run length is 1, ... |
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
test_array = [64, 25, 12, 22, 11]
sorted_array = insertion_sort(test_array)
print(f"Sorted a... | simplelr_Filter | [
{
"content": "Question:\nThis is not homework. This is for my personal exploration.\n\nI'm exploring different ways to implement sorting algorithms in Python.\n\nI've already implemented Bubble Sort and Selection Sort. Here is my code for Selection Sort:\n\n```python\ndef selection_sort(arr):\n for i in rang... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7730,
"level": 1,
"question": "This is not homework. This is for my personal exploration.\n\nI'm exploring different ways to implement sorting algorithms in Python.\n\nI've already implemented Bubble Sort and Selection Sort. Here is my code for Selection Sort:\n\n```python\ndef sele... |
def swap(a, b):
a, b = b, a
return a, b
# Example usage:
x = 5
y = 10
x, y = swap(x, y)
print(x, y) # Outputs: 10 5 | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to swap two integers without using any temporary variable in Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7731,
"level": 1,
"question": "Write a function to swap two integers without using any temporary variable in Python.",
"split": "train"
} |
def infix_to_postfix(s):
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
tokens = s.split()
stack = []
output = []
for token in tokens:
if token not in precedence and token not in '()':
output.append(token)
elif token == '(':
stack.append(token)
eli... | simplelr_Filter | [
{
"content": "Question:\nWrite a function to convert an infix expression to postfix notation. The function should handle basic arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), and parentheses for grouping. The input will be a string representing the infix expression, and th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7732,
"level": 1,
"question": "Write a function to convert an infix expression to postfix notation. The function should handle basic arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), and parentheses for grouping. The input will be a string repres... |
def separate(input_list):
evens = []
odds = []
for num in input_list:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens + odds | simplelr_Apps | [
{
"content": "Question:\nYour task is to implement a function that takes a list of integers as input and returns a new list with elements from the input list but sorted in such a way that all even numbers appear before all odd numbers. The relative order of even numbers and the relative order of odd numbers sho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7733,
"level": 1,
"question": "Your task is to implement a function that takes a list of integers as input and returns a new list with elements from the input list but sorted in such a way that all even numbers appear before all odd numbers. The relative order of even numbers and th... |
def is_valid(s: str) -> bool:
stack = []
bracket_map = {')': '(', '}': '{', ']': '['}
for char in s:
if char in ['(', '{', '[']:
stack.append(char)
else:
if not stack:
return False
top = stack.pop()
if top != bracket_map[char]:
... | simplelr_Data_Structure | [
{
"content": "Question:\nBalanced Bracket Validation\n\nYou are given a string `s` containing just the characters '(', ')', '{', '}', '[' and ']', and your task is to determine if the input string is valid.\n\nA string is considered valid if:\n1. The brackets must be closed in the correct order.\n2. Each type o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7734,
"level": 1,
"question": "Balanced Bracket Validation\n\nYou are given a string `s` containing just the characters '(', ')', '{', '}', '[' and ']', and your task is to determine if the input string is valid.\n\nA string is considered valid if:\n1. The brackets must be closed in... |
from collections import Counter
def frequency_array(A):
freq = Counter(A)
return [freq[x] for x in A]
# Example usage:
# A = [1, 2, 1, 3, 2, 1]
# B = construct_B(A)
# print(B) # Output: [3, 2, 3, 1, 2, 3] | simplelr_Filter | [
{
"content": "Question:\nWe are given an array A.\nFor each element, we calculate the frequency of its occurrence.\n\nWe then generate a new array B[i], \nsuch that B[i] = frequency of A[i]\n\nExample:\nLet A = [1, 2, 1, 3, 2, 1]\n\nHere's how to construct B:\n1. Frequency of 1 is 3 (occurring 3 times in A)\n2.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7735,
"level": 1,
"question": "We are given an array A.\nFor each element, we calculate the frequency of its occurrence.\n\nWe then generate a new array B[i], \nsuch that B[i] = frequency of A[i]\n\nExample:\nLet A = [1, 2, 1, 3, 2, 1]\n\nHere's how to construct B:\n1. Frequency of ... |
def countGreaterThanX(arr, X):
count = 0
for num in arr:
if num > X:
count += 1
return count
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, and an integer X, your task is to count how many elements in the list are greater than X.\n\nExample 1:\nInput:\narr = [1, 2, 3, 4, 5], X = 3\nOutput:\n2\nExplanation:\nThere are 2 elements greater than 3 (4 and 5).\n\nExample 2:\nInput:\narr = [10, 8, 5, 1, 7]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7736,
"level": 1,
"question": "Given a list of integers, and an integer X, your task is to count how many elements in the list are greater than X.\n\nExample 1:\nInput:\narr = [1, 2, 3, 4, 5], X = 3\nOutput:\n2\nExplanation:\nThere are 2 elements greater than 3 (4 and 5).\n\nExample... |
from collections import Counter
def has_triplet_with_sum(nums):
count = Counter(nums)
for c in nums:
for a in nums:
b = c - a
if b in count:
if a != b:
if count[a] >= 1 and count[b] >= 1:
return True
els... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to determine if a given list of integers contains a triplet (a, b, c) such that `a + b == c`. The function should return `True` if such a triplet exists, and `False` otherwise.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7737,
"level": 1,
"question": "Write a python function to determine if a given list of integers contains a triplet (a, b, c) such that `a + b == c`. The function should return `True` if such a triplet exists, and `False` otherwise.",
"split": "train"
} |
def circular_subarray_sum(arr, k):
total = sum(arr)
if total == k:
return True
seen = set([0])
current_sum = 0
for num in arr:
current_sum += num
if (current_sum - k) in seen:
return True
if total != k:
target = current_sum - (total - k)
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `arr` of size `n` and a target value `k`. The array is circular, meaning the next element of `arr[n-1]` is `arr[0]`. Your task is to determine if there exists a subarray (of at least one element) whose sum is exactly `k`. Return `true` if such a subarray e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7738,
"level": 1,
"question": "You are given an integer array `arr` of size `n` and a target value `k`. The array is circular, meaning the next element of `arr[n-1]` is `arr[0]`. Your task is to determine if there exists a subarray (of at least one element) whose sum is exactly `k`.... |
def count_words(s):
return len(s.split()) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that reads an input of type `string` and returns the count of words in the string. You should consider a word as any sequence of characters separated by spaces.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7739,
"level": 1,
"question": "Create a function that reads an input of type `string` and returns the count of words in the string. You should consider a word as any sequence of characters separated by spaces.",
"split": "train"
} |
def char_count(s):
s_lower = s.lower()
count_dict = {}
for char in s_lower:
if char in count_dict:
count_dict[char] += 1
else:
count_dict[char] = 1
return count_dict | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that accepts a string and returns a dictionary where the keys are the characters in the string, and the values are the number of times each character appears. Ensure the function accounts for both uppercase and lowercase versions of a character as the same charac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7740,
"level": 1,
"question": "Write a Python function that accepts a string and returns a dictionary where the keys are the characters in the string, and the values are the number of times each character appears. Ensure the function accounts for both uppercase and lowercase version... |
def is_monotonic(nums):
if len(nums) <= 1:
return True
is_increasing = True
is_decreasing = True
for i in range(len(nums) - 1):
if nums[i] > nums[i+1]:
is_increasing = False
elif nums[i] < nums[i+1]:
is_decreasing = False
return is_increasing or is_dec... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a list of integers is monotonically increasing or decreasing. A list is considered monotonically increasing if for all i <= j, nums[i] <= nums[j], and monotonically decreasing if for all i <= j, nums[i] >= nums[j].\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7741,
"level": 1,
"question": "Write a function to check if a list of integers is monotonically increasing or decreasing. A list is considered monotonically increasing if for all i <= j, nums[i] <= nums[j], and monotonically decreasing if for all i <= j, nums[i] >= nums[j].",
"spl... |
def longest_string(strings):
if not strings:
return None
longest_str = strings[0]
for string in strings[1:]:
if len(string) > len(longest_str):
longest_str = string
return longest_str | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of strings as input and returns the string with the maximum length. If there are multiple strings with the maximum length, return the first one found. If the list is empty, return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "user... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7742,
"level": 1,
"question": "Write a Python function that takes a list of strings as input and returns the string with the maximum length. If there are multiple strings with the maximum length, return the first one found. If the list is empty, return `None`.",
"split": "train"
} |
def two_sum(nums, target):
num_map = {}
for index, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], index]
num_map[num] = index
return [] | simplelr_Filter | [
{
"content": "Question:\nYou are given an array of integers `nums` and an integer `target`.\n\nFind the two numbers such that they add up to `target`.\n\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nYou can return the answer in any order.\n\nExam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7743,
"level": 1,
"question": "You are given an array of integers `nums` and an integer `target`.\n\nFind the two numbers such that they add up to `target`.\n\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nYou can retu... |
def factorial(n):
"""
Calculate the factorial of a given non-negative integer using recursion.
Args:
n (int): A non-negative integer.
Returns:
int: The factorial of n.
Raises:
TypeError: If n is not an integer.
ValueError: If n is a negative integer.
"""
if... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the factorial of a given number. The function should use recursion to achieve this. Ensure that the function handles edge cases, such as negative inputs or very large numbers efficiently.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7744,
"level": 1,
"question": "Write a function to calculate the factorial of a given number. The function should use recursion to achieve this. Ensure that the function handles edge cases, such as negative inputs or very large numbers efficiently.",
"split": "train"
} |
def get_top_books(books, n):
if not books:
raise ValueError("Books list cannot be empty")
if not isinstance(n, int) or n <= 0 or n > len(books):
raise ValueError("Invalid number of books requested")
books_with_index = [(title, score, idx) for idx, (title, score) in enumerate(books)]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nYou are developing a recommendation system for an online bookstore. Each book in the bookstore has been assigned a popularity score based on user interactions. Your task is to implement functionality that accurately recommends a specific number of the most popular books.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7745,
"level": 1,
"question": "### Scenario:\nYou are developing a recommendation system for an online bookstore. Each book in the bookstore has been assigned a popularity score based on user interactions. Your task is to implement functionality that accurately recommends a specific... |
def count_consecutive_ones(num: int) -> int:
binary_str = bin(num)[2:] # Convert to binary and remove the '0b' prefix
count = 0
in_sequence = False
for bit in binary_str:
if bit == '1':
if not in_sequence:
count += 1
in_sequence = True
else:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are given a non-negative integer `num`. Your task is to implement a function that converts the number into its equivalent binary string and then counts the number of consecutive sequences of '1's within that binary representation. \n\n### Function Signature\n`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7746,
"level": 1,
"question": "### Problem Statement\nYou are given a non-negative integer `num`. Your task is to implement a function that converts the number into its equivalent binary string and then counts the number of consecutive sequences of '1's within that binary representa... |
from typing import List
def sort_priorities(tasks: List[int]) -> None:
low = 0
mid = 0
high = len(tasks) - 1
while mid <= high:
if tasks[mid] == 0:
tasks[low], tasks[mid] = tasks[mid], tasks[low]
low += 1
mid += 1
elif tasks[mid] == 1:
mi... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nA popular app enables users to categorize their tasks by priority represented by three levels: High (0), Medium (1), and Low (2). The app needs to internally sort the tasks so that all High priority tasks come before Medium, and all Medium come before Low priority tasks.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7747,
"level": 1,
"question": "#### Scenario\nA popular app enables users to categorize their tasks by priority represented by three levels: High (0), Medium (1), and Low (2). The app needs to internally sort the tasks so that all High priority tasks come before Medium, and all Medi... |
def diamond(n):
if n <= 0:
return ''
max_width = 2 * n - 1
lines = []
for i in range(2 * n - 1):
d = abs(i - (n - 1))
s = max_width - 2 * d
line = ('*' * s).center(max_width)
lines.append(line + '\n')
return ''.join(lines)
| simplelr_Taco | [
{
"content": "Question:\nCreate a function that generates an ASCII representation of a diamond shape based on a given input dimension. The function should take a single integer input `n` representing the number of layers in the upper half of the diamond (including the middle layer). The lower half should be a m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7748,
"level": 1,
"question": "Create a function that generates an ASCII representation of a diamond shape based on a given input dimension. The function should take a single integer input `n` representing the number of layers in the upper half of the diamond (including the middle l... |
def bubble_sort_by_length(lst):
# Make a copy of the input list to avoid modifying the original list
strings = lst.copy()
n = len(strings)
# Traverse through all list elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n - i - 1):
# C... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python script to sort a list of strings by their lengths using a custom comparator function. In Python, you can use the `sorted()` function with a `key` parameter to sort by custom criteria. However, for the purpose of learning, implement the sorting manually using a sorting alg... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7749,
"level": 1,
"question": "Write a Python script to sort a list of strings by their lengths using a custom comparator function. In Python, you can use the `sorted()` function with a `key` parameter to sort by custom criteria. However, for the purpose of learning, implement the s... |
def even_sorted(arr):
return sorted(num for num in arr if num % 2 == 0) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in an array of integers and returns a new list containing only the even numbers. Additionally, the function should sort the returned list in ascending order. If there are no even numbers in the input array, the function should return an empty list.\nAnswer:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7750,
"level": 1,
"question": "Create a function that takes in an array of integers and returns a new list containing only the even numbers. Additionally, the function should sort the returned list in ascending order. If there are no even numbers in the input array, the function sho... |
import random
import string
def generate_password(length):
if length < 8:
print("Password length should be at least 8 characters.")
return None
all_characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(all_characters) for _ in range(length))... | simplelr_Filter | [
{
"content": "Question:\nfrom random import randint\nimport string\n\ndef generate_password(length):\n if length < 8:\n print(\"Password length should be at least 8 characters.\")\n return None\n all_characters = string.ascii_letters + string.digits + string.punctuation\n if length > len(... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7751,
"level": 1,
"question": "from random import randint\nimport string\n\ndef generate_password(length):\n if length < 8:\n print(\"Password length should be at least 8 characters.\")\n return None\n all_characters = string.ascii_letters + string.digits + strin... |
def max_sum_of_k_consecutive(nums, k):
if k <= 0 or len(nums) < k:
return -1
current_sum = sum(nums[:k])
max_sum = current_sum
for i in range(k, len(nums)):
current_sum = current_sum - nums[i - k] + nums[i]
if current_sum > max_sum:
max_sum = current_sum
return ma... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums` and an integer `k`, return the maximum sum of `k` consecutive elements in the array. If `nums` has fewer than `k` elements, return `-1`. Try to solve the problem in O(n) time complexity.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7752,
"level": 1,
"question": "Given an integer array `nums` and an integer `k`, return the maximum sum of `k` consecutive elements in the array. If `nums` has fewer than `k` elements, return `-1`. Try to solve the problem in O(n) time complexity.",
"split": "train"
} |
def frequency_counter(lst):
frequency_dict = {}
for num in lst:
if num in frequency_dict:
frequency_dict[num] += 1
else:
frequency_dict[num] = 1
return frequency_dict | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers, write an algorithm to calculate the frequency of each unique integer in the list and return a dictionary where the keys are the integers from the list and the values are their corresponding frequencies.\n\nYour input:\nA list of integers, which can include both... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7753,
"level": 1,
"question": "Given a list of integers, write an algorithm to calculate the frequency of each unique integer in the list and return a dictionary where the keys are the integers from the list and the values are their corresponding frequencies.\n\nYour input:\nA list ... |
def reverse_and_swap_case(s):
return ''.join([c.lower() if c.isupper() else c.upper() for c in s[::-1]]) | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that reverses the order of characters in a given string while also swapping the case of each letter?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7754,
"level": 1,
"question": "How can I create a Python function that reverses the order of characters in a given string while also swapping the case of each letter?",
"split": "train"
} |
import string
def custom_string_manipulation(s: str) -> str:
"""
Transforms the input string by reversing the order of words, removing punctuation, and converting to uppercase.
Parameters:
s (str): The input string.
Returns:
str: The transformed string.
"""
# Remove all punctuation fr... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement: Implement a Custom String Manipulation Function\n\nYou are tasked with implementing a custom string manipulation function that performs a series of operations on a given input string. The function should:\n\n1. Reverse the order of words in the string.\n2. Convert... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7755,
"level": 1,
"question": "### Problem Statement: Implement a Custom String Manipulation Function\n\nYou are tasked with implementing a custom string manipulation function that performs a series of operations on a given input string. The function should:\n\n1. Reverse the order ... |
from typing import List
def enhanced_bucket_sort(arr: List[int]) -> List[int]:
if not arr:
return []
n = len(arr)
if n == 1:
return arr
min_val = min(arr)
max_val = max(arr)
if min_val == max_val:
return arr
R = max_val - min_val + 1
k = min(R, n)
buckets = [... | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem: Enhanced Bucket Sort\n\nYou are tasked with implementing an enhanced version of the bucket sort algorithm. The new implementation must handle both negative and positive numbers efficiently. Moreover, it should dynamically determine the number of buckets based on the range o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7756,
"level": 1,
"question": "### Problem: Enhanced Bucket Sort\n\nYou are tasked with implementing an enhanced version of the bucket sort algorithm. The new implementation must handle both negative and positive numbers efficiently. Moreover, it should dynamically determine the num... |
import requests
def top_selling_books(category: str) -> list:
try:
url = 'https://api.bookstore.com/top_selling'
params = {'category': category}
response = requests.get(url, params=params)
response.raise_for_status()
except requests.exceptions.RequestException as e:
prin... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a Python function named `top_selling_books` that interacts with an online book store API to fetch data about best-selling books. The function should accept a single argument, `category`, which is a string representing the genre or category of books the user is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7757,
"level": 1,
"question": "You are required to write a Python function named `top_selling_books` that interacts with an online book store API to fetch data about best-selling books. The function should accept a single argument, `category`, which is a string representing the genr... |
def capitalize_list_strings(lst):
return [s.capitalize() for s in lst] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function called \"capitalize_list_strings\" that takes a list of strings as an argument and returns the list with each string capitalized.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7758,
"level": 1,
"question": "Write a Python function called \"capitalize_list_strings\" that takes a list of strings as an argument and returns the list with each string capitalized.",
"split": "train"
} |
def reachable_airports(flight_routes, starting_airport):
from collections import deque
# Build the adjacency list
adj = {}
for a, b in flight_routes:
if a not in adj:
adj[a] = []
if b not in adj:
adj[b] = []
adj[a].append(b)
adj[b].append(a)
... | simplelr_Apps | [
{
"content": "Question:\nYou are given a list of flight routes represented by pairs of cities. Each pair `(airport1, airport2)` means there is a direct flight from `airport1` to `airport2`. Write a function that takes the list of flight routes and a starting airport and returns a list of all the airports that a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7759,
"level": 1,
"question": "You are given a list of flight routes represented by pairs of cities. Each pair `(airport1, airport2)` means there is a direct flight from `airport1` to `airport2`. Write a function that takes the list of flight routes and a starting airport and return... |
from typing import List, Dict, Union
def find_top_k_profiles(profiles: List[Dict[str, Union[str, int]]], k: int) -> List[Dict[str, Union[str, int]]]:
# Sort the profiles by score descending and username ascending
sorted_profiles = sorted(profiles, key=lambda x: (-x['score'], x['username']))
# Return the to... | simplelr_Codeforces | [
{
"content": "Question:\nA tech company is working on a new software module that involves handling records of user profiles. Each user profile has a unique username, a score, and other metadata. The company wants to periodically filter the top-scoring user profiles for display.\n\nYou are tasked to write a func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7760,
"level": 1,
"question": "A tech company is working on a new software module that involves handling records of user profiles. Each user profile has a unique username, a score, and other metadata. The company wants to periodically filter the top-scoring user profiles for display... |
def print_value(d, k):
if k in d:
print(d[k])
else:
print("Key not found.") | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a dictionary and a key as an input, and prints out the value associated with that key. If the key does not exist, print \"Key not found.\"\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7761,
"level": 1,
"question": "Create a function that takes a dictionary and a key as an input, and prints out the value associated with that key. If the key does not exist, print \"Key not found.\"",
"split": "train"
} |
def is_parentheses_balanced(expression: str) -> bool:
stack = []
for char in expression:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Apps | [
{
"content": "Question:\nGiven a string `expression` consisting of lowercase letters, digits, and parentheses, implement a function that checks whether the parentheses are balanced and correctly nested. For the parentheses to be balanced, each opening parenthesis must have a corresponding closing parenthesis in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7762,
"level": 1,
"question": "Given a string `expression` consisting of lowercase letters, digits, and parentheses, implement a function that checks whether the parentheses are balanced and correctly nested. For the parentheses to be balanced, each opening parenthesis must have a c... |
def count_digits(n):
if n == 0:
return 1
if n < 0:
n = -n
count = 0
while n != 0:
n = n // 10
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes an integer as an input and prints the number of digits in the integer, without converting the integer to a string. Additionally, the function should be able to handle both positive and negative integers. You may not use any built-in Python functions... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7763,
"level": 1,
"question": "Write a function in Python that takes an integer as an input and prints the number of digits in the integer, without converting the integer to a string. Additionally, the function should be able to handle both positive and negative integers. You may no... |
def find_even_and_divisible_by_3(arr):
for num in arr:
if num % 6 == 0:
return num
return -1 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in an array of integers and returns the first element that is both even and divisible by 3, or return -1 if no such element exists in the array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7764,
"level": 1,
"question": "Create a function that takes in an array of integers and returns the first element that is both even and divisible by 3, or return -1 if no such element exists in the array.",
"split": "train"
} |
def count_a_in_first_n_characters(n, s):
return s[:n].count('a') | simplelr_Filter | [
{
"content": "Question:\nGenerate a Python function that takes an integer `n` and a string `s` as inputs and returns the number of times the character 'a' appears in the first `n` characters of the string `s`. If `n` is larger than the string's length, consider the whole string.\nAnswer:\nLet's think step by st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7765,
"level": 1,
"question": "Generate a Python function that takes an integer `n` and a string `s` as inputs and returns the number of times the character 'a' appears in the first `n` characters of the string `s`. If `n` is larger than the string's length, consider the whole strin... |
def get_indices(lst):
result = {}
for i, num in enumerate(lst):
if num not in result:
result[num] = [i]
else:
result[num].append(i)
return result | simplelr_Filter | [
{
"content": "Question:\nI have a list of numbers, and I want to write a function that takes this list and returns a dictionary where the keys are numbers from the list and the values are their indices in the list. My code looks like this:\n\n```python\ndef get_indices(lst):\n result = {}\n for i, num in ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7766,
"level": 1,
"question": "I have a list of numbers, and I want to write a function that takes this list and returns a dictionary where the keys are numbers from the list and the values are their indices in the list. My code looks like this:\n\n```python\ndef get_indices(lst):\n... |
def max_dict_value(d):
if not d:
return None
return max(d.values()) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the maximum value in a dictionary's values. If the dictionary is empty, return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7767,
"level": 1,
"question": "Write a Python function to find the maximum value in a dictionary's values. If the dictionary is empty, return `None`.",
"split": "train"
} |
def count_characters(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes in a string and outputs a dictionary where the keys are the characters in the string and the values are the counts of each character.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7768,
"level": 1,
"question": "Write a Python function that takes in a string and outputs a dictionary where the keys are the characters in the string and the values are the counts of each character.",
"split": "train"
} |
def fibonacci(n: int) -> int:
if n == 1:
return 0
elif n == 2:
return 1
a, b = 0, 1
for _ in range(2, n):
c = a + b
a = b
b = c
return b | simplelr_Evol | [
{
"content": "Question:\nYou are tasked with writing a function that takes an integer `n` and returns the `n`-th number in the Fibonacci sequence. The Fibonacci sequence is a series of numbers where the next number is found by adding up the two numbers before it. The sequence starts with 0 and 1. For example:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7769,
"level": 1,
"question": "You are tasked with writing a function that takes an integer `n` and returns the `n`-th number in the Fibonacci sequence. The Fibonacci sequence is a series of numbers where the next number is found by adding up the two numbers before it. The sequence ... |
def unique_users_per_device(log_file: str) -> dict[str, int]:
"""
Returns a dictionary where keys are device IDs and values
are the counts of unique user IDs per device ID.
"""
from collections import defaultdict
device_users = defaultdict(set)
with open(log_file, 'r') as file:
for ... | simplelr_Algorithm | [
{
"content": "Question:\n### Unique Users per Device ID Logging\n\nYou are tasked with creating a function that processes a log file containing user interactions within a mobile app. Each log entry records a user’s activity identified by a unique `user_id` and the device used identified by a `device_id`.\n\nYou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7770,
"level": 1,
"question": "### Unique Users per Device ID Logging\n\nYou are tasked with creating a function that processes a log file containing user interactions within a mobile app. Each log entry records a user’s activity identified by a unique `user_id` and the device used ... |
def get_histogram(input_list: list) -> dict:
histogram = {}
for num in input_list:
histogram[num] = histogram.get(num, 0) + 1
return histogram | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Histogram Calculation\n\nAs a data analyst, you've been given a list of numbers and tasked with visualizing the distribution of these numbers using a histogram. A histogram represents the frequency of each unique element within a list. Your task is to write a function `get... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7771,
"level": 1,
"question": "### Question: Histogram Calculation\n\nAs a data analyst, you've been given a list of numbers and tasked with visualizing the distribution of these numbers using a histogram. A histogram represents the frequency of each unique element within a list. Yo... |
def add(num1, num2):
return num1 + num2 | simplelr_Filter | [
{
"content": "Question:\nCan you explain how to create a simple addition function in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7772,
"level": 1,
"question": "Can you explain how to create a simple addition function in Python?",
"split": "train"
} |
def hex_to_decimal(hex_string):
return int(hex_string, 16) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that converts a hexadecimal (base 16) number to its decimal (base 10) equivalent. The function should take a string representing a hexadecimal number and return the corresponding decimal number as an integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7773,
"level": 1,
"question": "Create a function that converts a hexadecimal (base 16) number to its decimal (base 10) equivalent. The function should take a string representing a hexadecimal number and return the corresponding decimal number as an integer.",
"split": "train"
} |
def is_subsequence(sub, main):
sub_len = len(sub)
main_len = len(main)
if sub_len == 0:
return True
if main_len == 0:
return False
sub_ptr = 0
for char in main:
if sub_ptr < sub_len and char == sub[sub_ptr]:
sub_ptr += 1
return sub_ptr == su... | simplelr_Taco | [
{
"content": "Question:\nThe annual Tech Corp Hackathon is coming up, and one of the challenges focuses on string manipulation. The task is for participants to develop a function that can determine if one string is a subsequence of another.\n\nYour task is to:\n\n1) Create a function `is_subsequence(sub, main)`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7774,
"level": 1,
"question": "The annual Tech Corp Hackathon is coming up, and one of the challenges focuses on string manipulation. The task is for participants to develop a function that can determine if one string is a subsequence of another.\n\nYour task is to:\n\n1) Create a f... |
import pandas as pd
def double_dataframe(df):
return df * 2 | simplelr_Filter | [
{
"content": "Question:\nI want to generate a Python function that takes a pandas DataFrame and returns a new DataFrame with each row's values doubled. Each column in the DataFrame is expected to be numeric. How can I achieve this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7775,
"level": 1,
"question": "I want to generate a Python function that takes a pandas DataFrame and returns a new DataFrame with each row's values doubled. Each column in the DataFrame is expected to be numeric. How can I achieve this?",
"split": "train"
} |
from typing import List
def combination_sum(nums: List[int], target: int) -> int:
dp = [0] * (target + 1)
dp[0] = 1 # Base case: one way to make sum 0
for i in range(1, target + 1):
for num in nums:
if num <= i:
dp[i] += dp[i - num]
return dp[target] | simplelr_Data_Structure | [
{
"content": "Question:\n### Combination Sum Problem with Dynamic Programming\n\n**Objective**: Implement a function to find the number of combinations of elements from a given list that sum up to a target value using dynamic programming.\n\n**Context**: You are designing a software module that needs to calcula... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7776,
"level": 1,
"question": "### Combination Sum Problem with Dynamic Programming\n\n**Objective**: Implement a function to find the number of combinations of elements from a given list that sum up to a target value using dynamic programming.\n\n**Context**: You are designing a so... |
def find_sentence_with_conjunction(sentences):
for index, sentence in enumerate(sentences):
if 'but' in sentence.lower() or 'however' in sentence.lower():
return index
return -1 | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of sentences and identifies the sentence that contains the word \"but\" or \"however\". The function should return the index of the sentence if found, otherwise return -1. If there are multiple sentences containing \"but\" or \"however\", retur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7777,
"level": 1,
"question": "Create a Python function that takes a list of sentences and identifies the sentence that contains the word \"but\" or \"however\". The function should return the index of the sentence if found, otherwise return -1. If there are multiple sentences conta... |
def longest_common_subsequence(s1, s2):
m = len(s1)
n = len(s2)
# Create a table with (m+1) rows and (n+1) columns initialized to 0
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] ... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes two strings as input and returns the length of the longest common subsequence. A subsequence is a sequence derived by deleting some or none of the characters without changing the order of the remaining characters.\n\nInput: Two strings s1 and s2\nOutput: An i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7778,
"level": 1,
"question": "Write a function that takes two strings as input and returns the length of the longest common subsequence. A subsequence is a sequence derived by deleting some or none of the characters without changing the order of the remaining characters.\n\nInput: ... |
def process_array(operations):
"""
Process a series of operations on an array of integers.
Args:
operations (list of tuples): Each tuple contains an operation name
and arguments required for the operation.
Returns:
list: A list of results for each query-type o... | simplelr_Docs | [
{
"content": "Question:\nYou are tasked with implementing a Python function that processes numeric data stored in an array efficiently.\n\n#### Problem Statement:\n\nGiven an array of integers, you need to perform the following operations:\n\n1. **Insert an element:** Insert a new element at the specified index... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7779,
"level": 1,
"question": "You are tasked with implementing a Python function that processes numeric data stored in an array efficiently.\n\n#### Problem Statement:\n\nGiven an array of integers, you need to perform the following operations:\n\n1. **Insert an element:** Insert a... |
from typing import List, Dict, Union
def search_items(items: List[Dict[str, Union[int, str]]], keyword: str) -> List[Dict[str, Union[int, str]]]:
keyword_lower = keyword.lower()
result = []
for item in items:
title_lower = item['title'].lower()
desc_lower = item['description'].lower()
... | simplelr_Evol | [
{
"content": "Question:\nThere is a popular online marketplace where sellers can list items, and buyers can search for items by keyword. Implement a function `search_items` that takes a list of items and a search keyword, and returns a list of items that contain the keyword. Each item is represented as a dictio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7780,
"level": 1,
"question": "There is a popular online marketplace where sellers can list items, and buyers can search for items by keyword. Implement a function `search_items` that takes a list of items and a search keyword, and returns a list of items that contain the keyword. E... |
def multiply_neighbors(arr):
result = []
for i in range(1, len(arr) - 1):
product = arr[i] * arr[i + 1]
result.append(product)
return result | simplelr_Filter | [
{
"content": "Question:\nGiven array\\_1 = [5, 10, 5, 10, 5, 10, 5, 10], write a Python function to multiply neighboring elements in the given array and return a new array with the result of the multiplication. Additionally, the function should exclude the first and last elements from being multiplied.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7781,
"level": 1,
"question": "Given array\\_1 = [5, 10, 5, 10, 5, 10, 5, 10], write a Python function to multiply neighboring elements in the given array and return a new array with the result of the multiplication. Additionally, the function should exclude the first and last eleme... |
import itertools
def generate_strings(s):
underscores = [i for i, c in enumerate(s) if c == '_']
letters = [chr(ord('a') + i) for i in range(26)]
n = len(underscores)
result = []
for repl_tuple in itertools.product(letters, repeat=n):
current = []
repl_iter = iter(repl_tuple)
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` that contains lowercase English letters and can include underscores (`_`). An underscore can replace any single lowercase English letter, potentially creating multiple valid words. Your task is to return the list of all possible distinct strings formed after r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7782,
"level": 1,
"question": "You are given a string `s` that contains lowercase English letters and can include underscores (`_`). An underscore can replace any single lowercase English letter, potentially creating multiple valid words. Your task is to return the list of all possi... |
def sum_with_validation(a, b, c):
if a < 0 or b < 0 or c < 0:
return -1
return a + b + c | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes three integers as input and returns the sum of the numbers. If any of the numbers are below 0, the function should return -1. What are you testing?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7783,
"level": 1,
"question": "Create a function that takes three integers as input and returns the sum of the numbers. If any of the numbers are below 0, the function should return -1. What are you testing?",
"split": "train"
} |
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
# Create a flag that will allow the function to terminate early if there's nothing left to sort
# Start looking at each element, up to n-i-1
for j in range(0, n - i - 1):
# Compare the element to th... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code for bubble sort algorithm and explain how it works.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7784,
"level": 1,
"question": "Write a Python code for bubble sort algorithm and explain how it works.",
"split": "train"
} |
def balanced_brackets(s: str) -> bool:
stack = []
opening = {'(', '[', '{'}
closing_to_opening = {')': '(', ']': '[', '}': '{'}
for c in s:
if c in opening:
stack.append(c)
elif c in closing_to_opening:
if not stack:
return False
t... | simplelr_Taco | [
{
"content": "Question:\n## Task\nImplement a function `balanced_brackets` that takes a single string input containing various types of brackets: round `()`, square `[]`, and curly `{}`. The function should return `True` if the string contains a balanced sequence of brackets, otherwise return `False`. A sequenc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7785,
"level": 1,
"question": "## Task\nImplement a function `balanced_brackets` that takes a single string input containing various types of brackets: round `()`, square `[]`, and curly `{}`. The function should return `True` if the string contains a balanced sequence of brackets, ... |
def max_profit(prices):
if len(prices) < 2:
return 0
min_price = prices[0]
max_profit = -float('inf')
for price in prices[1:]:
current_profit = price - min_price
if current_profit > max_profit:
max_profit = current_profit
if price < min_price:
min_... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the maximum profit from the given prices of stocks over a period of time. The function should take a list of stock prices and return the maximum profit that can be made by buying and selling stocks at the correct times. Note that you can only make a single buy a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7786,
"level": 1,
"question": "Write a function to find the maximum profit from the given prices of stocks over a period of time. The function should take a list of stock prices and return the maximum profit that can be made by buying and selling stocks at the correct times. Note th... |
def can_split_into_k_subarrays(arr, k):
total = sum(arr)
n = len(arr)
if n < k or total % k != 0:
return False
target = total // k
current_sum = 0
count = 0
for num in arr:
current_sum += num
if current_sum == target:
count += 1
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr` and an integer `k`, find out if it is possible to split the array into `k` non-empty subarrays such that each subarray has the same sum. Return `true` if it is possible, otherwise return `false`.\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7787,
"level": 1,
"question": "Given an array of integers `arr` and an integer `k`, find out if it is possible to split the array into `k` non-empty subarrays such that each subarray has the same sum. Return `true` if it is possible, otherwise return `false`.",
"split": "train"
} |
def ball_arrangement(n):
old = list(range(1, n + 1))
new = [old[(j + 1) % n] for j in range(n)]
return new | simplelr_Leetcode | [
{
"content": "Question:\nThere are `n` people standing in a circle, labeled from `1` to `n` in a clockwise direction. Each person holds a ball with a unique number from `1` to `n` written on it. At the beginning, each person has a ball whose number matches their label. The game consists of each person passing t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7788,
"level": 1,
"question": "There are `n` people standing in a circle, labeled from `1` to `n` in a clockwise direction. Each person holds a ball with a unique number from `1` to `n` written on it. At the beginning, each person has a ball whose number matches their label. The gam... |
import math
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
max_divisor = math.sqrt(n)
for i in range(3, int(max_divisor) + 1, 2):
if n % i == 0:
return False
return True | simplelr_Filter | [
{
"content": "Question:\nExplain how to create a Python function that checks if a given number is a prime number.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7789,
"level": 1,
"question": "Explain how to create a Python function that checks if a given number is a prime number.",
"split": "train"
} |
from collections import Counter
def most_common_element(lst):
if not lst:
return None # or raise ValueError("List is empty")
counts = Counter(lst)
return counts.most_common(1)[0][0] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the most common element in a list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7790,
"level": 1,
"question": "Write a python function to find the most common element in a list.",
"split": "train"
} |
def numTrees(n):
dp = [0] * (n + 1)
dp[0] = 1 # Base case: one empty tree
for i in range(1, n + 1):
for j in range(1, i + 1):
dp[i] += dp[j - 1] * dp[i - j]
return dp[n] | simplelr_Apps | [
{
"content": "Question:\nGiven a positive integer n, count all possible distinct binary search trees (BST) that can be made using values from 1 to n.\n\nExample:\nInput: 3\nOutput: 5\nExplanation: The 5 BSTs are:\n 1 3 3 2 1\n \\ / / / \\ \\\n 3 2 1 ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7791,
"level": 1,
"question": "Given a positive integer n, count all possible distinct binary search trees (BST) that can be made using values from 1 to n.\n\nExample:\nInput: 3\nOutput: 5\nExplanation: The 5 BSTs are:\n 1 3 3 2 1\n \\ / / /... |
import html
def process_html_content(user_input: str, reverse: bool = False) -> str:
"""
Process the given user input string for safe HTML display or revert it back to the original content.
Parameters:
user_input (str): The input string containing user content.
reverse (bool): A flag indicating wh... | simplelr_Docs | [
{
"content": "Question:\nYou are tasked with creating a simple web content management feature that safely processes user-generated content. The goal is to properly escape HTML characters when displaying user input and then reverse the process to reveal the original content when loading it back for editing.\n\n#... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7792,
"level": 1,
"question": "You are tasked with creating a simple web content management feature that safely processes user-generated content. The goal is to properly escape HTML characters when displaying user input and then reverse the process to reveal the original content whe... |
def largest_rectangle_area(heights: list) -> int:
stack = [-1] # Initialize stack with base index
max_area = 0
n = len(heights)
for i in range(n):
while stack[-1] != -1 and heights[i] < heights[stack[-1]]:
j = stack.pop()
width = i - stack[-1] - 1
area =... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of integers representing the heights of buildings arranged in a row. Each building is of the same width, and the heights are provided from left to right. You are tasked to calculate the largest rectangular area that can be formed by using any number of contiguous bu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7793,
"level": 1,
"question": "You are given a list of integers representing the heights of buildings arranged in a row. Each building is of the same width, and the heights are provided from left to right. You are tasked to calculate the largest rectangular area that can be formed b... |
def first_non_repeating_character(s):
if not s:
return -1
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
for i, char in enumerate(s):
if counts[char] == 1:
return i
return -1 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the first non-repeating character in a given string and return its index. If there is no such character, return -1. For example, for the string \"leetcode\", the function should return 0, as 'l' is the first non-repeating character. If the string is \"lov... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7794,
"level": 1,
"question": "Write a Python function to find the first non-repeating character in a given string and return its index. If there is no such character, return -1. For example, for the string \"leetcode\", the function should return 0, as 'l' is the first non-repeatin... |
from collections import deque
def shortest_subarray_with_sum(nums: list[int], k: int) -> int:
prefix = [0]
for num in nums:
prefix.append(prefix[-1] + num)
dq = deque()
res = float('inf')
for i in range(len(prefix)):
# Maintain deque in increasing order of prefix[j]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given a list of integers `nums` and an integer `k`. Your goal is to find the length of the shortest subarray with a sum equal to or greater than `k`. \n\nIf no such subarray exists, return -1.\n\n### Function Signature\n```python\ndef shortest_subarray_w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7795,
"level": 1,
"question": "### Problem Statement\n\nYou are given a list of integers `nums` and an integer `k`. Your goal is to find the length of the shortest subarray with a sum equal to or greater than `k`. \n\nIf no such subarray exists, return -1.\n\n### Function Signature\... |
def caesar_cipher_encrypt(plaintext, shift):
result = []
for char in plaintext:
if char.isalpha():
if char.islower():
base = ord('a')
else:
base = ord('A')
offset = ord(char) - base
new_offset = (offset + shift) % 26
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to encrypt a message using Caesar cipher. The function should take in two parameters: the plain text and the shift value. The function should only encrypt alphabetic characters and ignore other characters. The shift should wrap around, i.e., 'z' shifted by 1 shou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7796,
"level": 1,
"question": "Write a python function to encrypt a message using Caesar cipher. The function should take in two parameters: the plain text and the shift value. The function should only encrypt alphabetic characters and ignore other characters. The shift should wrap ... |
from typing import List, Dict
def evaluate_department_performance(reviews: List[Dict[str, int]]) -> str:
sum_work = sum(review['work_quality'] for review in reviews)
sum_team = sum(review['teamwork'] for review in reviews)
sum_deadline = sum(review['deadline_adherence'] for review in reviews)
n = len(r... | simplelr_Taco | [
{
"content": "Question:\nYou are working on a project where different departments' performance needs to be evaluated based on a composite score. Each department provides an array of review objects that include `work_quality`, `teamwork`, and `deadline_adherence`, each rated out of 10. \n\nWrite a function that ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7797,
"level": 1,
"question": "You are working on a project where different departments' performance needs to be evaluated based on a composite score. Each department provides an array of review objects that include `work_quality`, `teamwork`, and `deadline_adherence`, each rated ou... |
from collections import deque
from typing import List, Tuple
def can_reach_target(grid: List[List[str]], start: Tuple[int, int], target: Tuple[int, int]) -> bool:
if start == target:
return True
rows = len(grid)
cols = len(grid[0]) if rows > 0 else 0
visited = set()
queue = deque(... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nYou are developing a text-based game which involves moving a player on a 2D grid. Each cell on the grid may be free space (.) or an obstacle (#). The player can only move to adjacent free space cells (up, down, left, right).\n\n### Description\nImplement a function that det... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7798,
"level": 1,
"question": "### Context\nYou are developing a text-based game which involves moving a player on a 2D grid. Each cell on the grid may be free space (.) or an obstacle (#). The player can only move to adjacent free space cells (up, down, left, right).\n\n### Descrip... |
def swap_a_b(s):
translation_table = str.maketrans('ab', 'ba')
return s.translate(translation_table) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and returns a new string where all the characters 'a' are replaced with 'b', and all the characters 'b' are replaced with 'a'. This should be done without using any conditional statements or loops.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7799,
"level": 1,
"question": "Create a function that takes a string as input and returns a new string where all the characters 'a' are replaced with 'b', and all the characters 'b' are replaced with 'a'. This should be done without using any conditional statements or loops.",
"sp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.