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 factorial(n): if n < 0: raise ValueError("n must be a non-negative integer") elif n == 0 or n == 1: return 1 else: return n * factorial(n - 1)
simplelr_Filter
[ { "content": "Question:\nCan you provide a detailed explanation of how to create a Python function that calculates the factorial of a number using recursion? Could you also include a few examples of how to use this function?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5600, "level": 1, "question": "Can you provide a detailed explanation of how to create a Python function that calculates the factorial of a number using recursion? Could you also include a few examples of how to use this function?", "split": "train" }
def generate_grid_coordinates(width, height): if width <= 0 or height <= 0: return [] return [[(x, y) for x in range(width)] for y in range(height)]
simplelr_Filter
[ { "content": "Question:\nCreate a Python function to generate a list of tuples representing the coordinates of a grid. The function should accept two parameters: `width` and `height`, which define the dimensions of the grid. The coordinates should start from (0, 0) and go up to (width-1, height-1). The tuples s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5601, "level": 1, "question": "Create a Python function to generate a list of tuples representing the coordinates of a grid. The function should accept two parameters: `width` and `height`, which define the dimensions of the grid. The coordinates should start from (0, 0) and go up t...
def max_subarray_sum(arr): if not arr: return 0 max_ending_here = max_so_far = arr[0] for num in arr[1:]: max_ending_here = max(num, max_ending_here + num) max_so_far = max(max_so_far, max_ending_here) return max_so_far
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the maximum subarray sum. This function should return the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum. The function should be designed to efficiently use minimal space and time.\nAnswer:\nLet's think step by ste...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5602, "level": 1, "question": "Write a function to find the maximum subarray sum. This function should return the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum. The function should be designed to efficiently use minimal space and time...
def sum_of_evens(nums): total = 0 for num in nums: if num % 2 == 0: total += num return total
simplelr_Filter
[ { "content": "Question:\nThe following is a sample interview question for a software developer position:\n\n\"Given an array of integers, find the sum of all the even numbers in the array.\"\n\nHere is a potential solution written in Python:\n\n```python\ndef sum_of_evens(nums):\n \"\"\"\n This function takes...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5603, "level": 1, "question": "The following is a sample interview question for a software developer position:\n\n\"Given an array of integers, find the sum of all the even numbers in the array.\"\n\nHere is a potential solution written in Python:\n\n```python\ndef sum_of_evens(nums...
from typing import List def cycle_sort(arr: List[int]) -> List[int]: if not arr: return [] n = len(arr) sorted_arr = sorted(arr) pos = {v: i for i, v in enumerate(sorted_arr)} for i in range(n): if arr[i] == sorted_arr[i]: continue start = i ...
simplelr_Data_Structure
[ { "content": "Question:\nYou are given an array of distinct integers. Your task is to implement the `cycle_sort` function that sorts the array using the Cycle Sort algorithm. The function should sort the array in-place and return the sorted array.\n\n### Function Signature\n\n```python\ndef cycle_sort(arr: List...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5604, "level": 1, "question": "You are given an array of distinct integers. Your task is to implement the `cycle_sort` function that sorts the array using the Cycle Sort algorithm. The function should sort the array in-place and return the sorted array.\n\n### Function Signature\n\n...
def is_palindrome(s): # Preprocess the string: keep only alphanumeric characters and convert to lowercase filtered = [char.lower() for char in s if char.isalnum()] s_filtered = ''.join(filtered) stack = [] for char in s_filtered: stack.append(char) for char in s_filtered: ...
simplelr_Filter
[ { "content": "Question:\nCan you determine if a string is a palindrome using a stack data structure?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5605, "level": 1, "question": "Can you determine if a string is a palindrome using a stack data structure?", "split": "train" }
def length_of_longest_substring(s): last_seen = {} max_length = 0 left = 0 for right in range(len(s)): char = s[right] if char in last_seen and last_seen[char] >= left: left = last_seen[char] + 1 last_seen[char] = right current_length = right - left + 1 ...
simplelr_Filter
[ { "content": "Question:\nGiven a string, find the length of the longest substring without repeating characters.\n\nExample:\n\nInput: \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\n\nExample:\n\nInput: \"bbbbb\"\nOutput: 1\nExplanation: The answer is \"b\", with the length o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5606, "level": 1, "question": "Given a string, find the length of the longest substring without repeating characters.\n\nExample:\n\nInput: \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\n\nExample:\n\nInput: \"bbbbb\"\nOutput: 1\nExplanation: The...
def find_maximum(x, y): if x == y: return x diff = x ^ y mask = 1 << (diff.bit_length() - 1) return x if (x & mask) else y
simplelr_Filter
[ { "content": "Question:\nGiven two numbers x and y, write a Python program to find the maximum between x and y using bitwise operators.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5607, "level": 1, "question": "Given two numbers x and y, write a Python program to find the maximum between x and y using bitwise operators.", "split": "train" }
def removeKChars(s, k): stack = [] for char in s: while stack and k > 0 and stack[-1] < char: stack.pop() k -= 1 stack.append(char) # If there are remaining k, remove from the end if k > 0: stack = stack[:-k] return ''.join(stack)
simplelr_Taco
[ { "content": "Question:\nGiven a string s and an integer k, the task is to remove k characters from the string such that the resulting string is the largest lexicographically possible. You need to complete the function `removeKChars` which takes a string `s` and an integer `k` as input and returns the largest l...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5608, "level": 1, "question": "Given a string s and an integer k, the task is to remove k characters from the string such that the resulting string is the largest lexicographically possible. You need to complete the function `removeKChars` which takes a string `s` and an integer `k`...
import re def unique_word_count(sentence): """ A function that finds the number of unique words in a sentence. Args: sentence (string): A string representing a sentence. Returns: int: The number of unique words in the sentence. """ # Replace all non-word, non-space, and non-ap...
simplelr_Package
[ { "content": "Question:\nIn this problem, you need to write a function `unique_word_count` that computes the number of unique words in a given string. The input string will be a sentence, and the words will be separated by spaces. The function should remove any punctuation and consider words case-insensitively ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5609, "level": 1, "question": "In this problem, you need to write a function `unique_word_count` that computes the number of unique words in a given string. The input string will be a sentence, and the words will be separated by spaces. The function should remove any punctuation and...
def k_reverse(arr: list, k: int) -> list: """ :param arr: a list of integers :param k: length of sublists to reverse :return: a list with every sublist of length k reversed Raises: ValueError: If k is not a positive integer. """ if not isinstance(k, int) or k <= 0: raise Val...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given a list of integers. Your task is to implement a function that performs a \"k-reverse\" on the list. The \"k-reverse\" operation involves reversing every contiguous sublist of length `k`. If the number of elements in the list is not a multiple of `k...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5610, "level": 1, "question": "### Problem Statement\n\nYou are given a list of integers. Your task is to implement a function that performs a \"k-reverse\" on the list. The \"k-reverse\" operation involves reversing every contiguous sublist of length `k`. If the number of elements ...
def reverse_list(lst): return lst[::-1] # Example usage: numbers = [1, 2, 3, 4, 5] reversed_numbers = reverse_list(numbers) print(reversed_numbers) # Output: [5, 4, 3, 2, 1]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to reverse a list. Implement this function using list slicing.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5611, "level": 1, "question": "Write a python function to reverse a list. Implement this function using list slicing.", "split": "train" }
from typing import List def has_pair_with_sum(nums: List[int], target: int) -> bool: seen = set() for num in nums: complement = target - num if complement in seen: return True seen.add(num) return False
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given an array of integers and a target sum. Your task is to write a function to determine if there exists a pair of numbers in the array whose sum is equal to the target sum.\n\n### Function Signature\n```python\ndef has_pair_with_sum(nums: List[int], t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5612, "level": 1, "question": "### Problem Statement\n\nYou are given an array of integers and a target sum. Your task is to write a function to determine if there exists a pair of numbers in the array whose sum is equal to the target sum.\n\n### Function Signature\n```python\ndef h...
def findSingleNumber(nums): res = 0 for num in nums: res ^= num return res
simplelr_Taco
[ { "content": "Question:\nGiven an integer array `nums` where every element appears twice except for one, which appears exactly once. Find that single one.\n\nExample 1:\nInput: nums = [2,2,1]\nOutput: 1\n\nExample 2:\nInput: nums = [4,1,2,1,2]\nOutput: 4\n\nExample 3:\nInput: nums = [1]\nOutput: 1\n\nYour Task:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5613, "level": 1, "question": "Given an integer array `nums` where every element appears twice except for one, which appears exactly once. Find that single one.\n\nExample 1:\nInput: nums = [2,2,1]\nOutput: 1\n\nExample 2:\nInput: nums = [4,1,2,1,2]\nOutput: 4\n\nExample 3:\nInput: ...
def look_and_say(n: int) -> str: term = "1" if n == 1: return term for _ in range(n - 1): next_term = [] count = 1 current = term[0] for c in term[1:]: if c == current: count += 1 else: next_term.append(str(count...
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes an integer `n` and generates the nth sequence in the \"Look-and-say\" sequence.\n\nThe \"Look-and-say\" sequence is a sequence of integers where each term is the result of reading aloud the digits of the previous term. Starting with \"1\", the \"Look-and-say\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5614, "level": 1, "question": "Write a function that takes an integer `n` and generates the nth sequence in the \"Look-and-say\" sequence.\n\nThe \"Look-and-say\" sequence is a sequence of integers where each term is the result of reading aloud the digits of the previous term. Start...
from typing import List def split_string(s: str) -> List[str]: if not s: return [] result = [] current_sub = s[0] current_type = current_sub.isalpha() for c in s[1:]: c_type = c.isalpha() if c_type == current_type: current_sub += c else: resul...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Description\n\nGiven a string `s` that consists of both alphabets and digits, split the string into substrings such that each substring contains either only alphabets or only digits. Return a list of the substrings in the order they appear in the input string.\n\n### Functio...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5615, "level": 1, "question": "### Problem Description\n\nGiven a string `s` that consists of both alphabets and digits, split the string into substrings such that each substring contains either only alphabets or only digits. Return a list of the substrings in the order they appear ...
def calculate_average(numbers): """Calculates the average of a list of numbers. Args: numbers (list): A list of integers or floats. Returns: float: The average of the numbers. Returns 0.0 if the list is empty. Examples: >>> calculate_average([1, 2, 3, 4]) 2.5 >...
simplelr_Filter
[ { "content": "Question:\nWrite a Python program that calculates the average of a list of numbers. The program should take a list of numbers as input and return the average. If the list is empty, the program should return 0.0. Ensure your code is well-documented and follows best practices.\nAnswer:\nLet's think ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5616, "level": 1, "question": "Write a Python program that calculates the average of a list of numbers. The program should take a list of numbers as input and return the average. If the list is empty, the program should return 0.0. Ensure your code is well-documented and follows bes...
import sympy as sp def find_matching_indices(array): return [i for i, x in enumerate(array) if x == 0] # Testing the function arr = [1, 2, 0, 0, 0, 3, 4, 0] print(find_matching_indices(arr))
simplelr_Filter
[ { "content": "Question:\nimport sympy as sp\n\ndef find_matching_elements(array):\n return [x for x in array if sp.simplify(x - 0) == 0]\n\n# Testing the function\narr = [1, 2, 0, 0, 0, 3, 4, 0]\nprint(find_matching_elements(arr))\n\nI want to write a similar function but it only returns the indices of the m...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5617, "level": 1, "question": "import sympy as sp\n\ndef find_matching_elements(array):\n return [x for x in array if sp.simplify(x - 0) == 0]\n\n# Testing the function\narr = [1, 2, 0, 0, 0, 3, 4, 0]\nprint(find_matching_elements(arr))\n\nI want to write a similar function but i...
def find_missing_numbers(numbers): if not numbers: return [] m = max(numbers) expected = set(range(1, m + 1)) actual = set(numbers) missing = sorted(expected - actual) return missing
simplelr_Filter
[ { "content": "Question:\ndef find_missing_numbers(numbers):\n n = len(numbers)\n expected_sum = (n * (n + 1)) // 2\n actual_sum = sum(numbers)\n missing_sum = expected_sum - actual_sum\n return [i for i in range(1, n + 1) if i not in numbers and i <= missing_sum]\n\nnumbers = [1, 2, 3, 5]\nprint(...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5618, "level": 1, "question": "def find_missing_numbers(numbers):\n n = len(numbers)\n expected_sum = (n * (n + 1)) // 2\n actual_sum = sum(numbers)\n missing_sum = expected_sum - actual_sum\n return [i for i in range(1, n + 1) if i not in numbers and i <= missing_sum...
def check_integers_with_zero(lst): has_zero = False for item in lst: if type(item) is not int: return False if item == 0: has_zero = True return has_zero
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if all elements in the given list are integers and at least one of them is zero. Your function should return `True` if these conditions are met, and `False` otherwise.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5619, "level": 1, "question": "Write a python function to check if all elements in the given list are integers and at least one of them is zero. Your function should return `True` if these conditions are met, and `False` otherwise.", "split": "train" }
def uncompress(S): result = [] i = 0 while i < len(S): char = S[i] i += 1 num_str = '' while i < len(S) and S[i].isdigit(): num_str += S[i] i += 1 count = int(num_str) if num_str else 1 result.append(char * count) return ''.join(res...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `S` representing a compressed version of a string where consecutive repeated characters are represented as the character followed by the number of repetitions. For example, the string \"a3b2\" would be uncompressed to \"aaabb\". Write a function `uncompress` that ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5620, "level": 1, "question": "You are given a string `S` representing a compressed version of a string where consecutive repeated characters are represented as the character followed by the number of repetitions. For example, the string \"a3b2\" would be uncompressed to \"aaabb\". ...
from collections import Counter import heapq def find_top_k_frequent_words(words: list[str], k: int) -> list[str]: if not words or k == 0: return [] freq = Counter(words) heap = [] for word, count in freq.items(): if len(heap) < k: heapq.heappush(heap, (count, word)) ...
simplelr_Package
[ { "content": "Question:\nYou are asked to write a function `find_top_k_frequent_words` that takes a list of strings `words` and an integer `k` as its arguments. The function should return a list of the `k` most frequent words in the `words` list, sorted by their frequency in descending order. In case of a tie, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5621, "level": 1, "question": "You are asked to write a function `find_top_k_frequent_words` that takes a list of strings `words` and an integer `k` as its arguments. The function should return a list of the `k` most frequent words in the `words` list, sorted by their frequency in d...
def convert_and_square_list(lst): return ','.join(str(x ** 2) for x in lst)
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that converts a list of integers into a comma-separated string, with each integer squared? For example, if I provide the list `[1, 2, 3]`, the function should return `\"1,4,9\"`. How can I achieve this?\nAnswer:\nLet's think step by step.\n", "role...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5622, "level": 1, "question": "How can I create a Python function that converts a list of integers into a comma-separated string, with each integer squared? For example, if I provide the list `[1, 2, 3]`, the function should return `\"1,4,9\"`. How can I achieve this?", "split": "...
import math def sqrt(number): return math.sqrt(number)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to return the square root of a given number.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5623, "level": 1, "question": "Write a python function to return the square root of a given number.", "split": "train" }
def select_event_loop(platform_name: str, version: float) -> str: if platform_name == 'Windows': return 'ProactorEventLoop' elif platform_name == 'macOS': if version <= 10.8: return 'SelectSelector' else: return 'KqueueSelector' else: return 'UnknownEv...
simplelr_Docs
[ { "content": "Question:\n### Asyncio Event Loop Compatibility Checking\n\n**Objective**: Write a Python function that determines the appropriate asyncio event loop for the given platform and version constraints.\n\n**Instructions**:\n1. Implement a function `select_event_loop(platform_name: str, version: float)...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5624, "level": 1, "question": "### Asyncio Event Loop Compatibility Checking\n\n**Objective**: Write a Python function that determines the appropriate asyncio event loop for the given platform and version constraints.\n\n**Instructions**:\n1. Implement a function `select_event_loop(...
def sum_above_average(arr): if not arr: return 0 total_sum = sum(arr) average = total_sum / len(arr) greater_sum = 0 for num in arr: if num > average: greater_sum += num return greater_sum
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an array of integers and returns the sum of all the elements that are greater than the average of the array.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5625, "level": 1, "question": "Create a function that takes an array of integers and returns the sum of all the elements that are greater than the average of the array.", "split": "train" }
def shortest_distance(cards): last_occurrence = {} min_dist = float('inf') for i, num in enumerate(cards): if num in last_occurrence: distance = i - last_occurrence[num] if distance < min_dist: min_dist = distance last_occurrence[num] = i e...
simplelr_Leetcode
[ { "content": "Question:\nYou have two friends Alice and Bob playing a memory card game where they need to remember the sequence of the cards. Alice will play by showing Bob an array of integers `cards` where each integer represents a card's value. Bob's task is to find any repeated card within this array and de...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5626, "level": 1, "question": "You have two friends Alice and Bob playing a memory card game where they need to remember the sequence of the cards. Alice will play by showing Bob an array of integers `cards` where each integer represents a card's value. Bob's task is to find any rep...
def int_list_to_binary_string(lst): binary_str = '' for num in lst: byte_value = num % 256 binary_str += format(byte_value, '08b') return binary_str
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python function that converts a list of integers to a binary string where each integer is represented in 8 bits?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5627, "level": 1, "question": "Can you provide a Python function that converts a list of integers to a binary string where each integer is represented in 8 bits?", "split": "train" }
def sum_of_multiples(n): total = 0 for i in range(1, n): if i % 3 == 0 or i % 5 == 0: total += i return total
simplelr_Apps
[ { "content": "Question:\nIn Python and other programming languages, a `for` loop is used when you know how many times you want to iterate a statement or a block of statements. This is in contrast to a `while` loop, which is used for indefinite iteration, where you keep iterating as long as some condition is tru...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5628, "level": 1, "question": "In Python and other programming languages, a `for` loop is used when you know how many times you want to iterate a statement or a block of statements. This is in contrast to a `while` loop, which is used for indefinite iteration, where you keep iterati...
from typing import List, Dict from datetime import datetime def get_overdue_books(loans: List[Dict[str, str]], current_date: str) -> List[Dict[str, str]]: overdue_books = [] current = datetime.strptime(current_date, "%Y-%m-%d") for loan in loans: due_date = datetime.strptime(loan["due_date"], ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are developing a library management system that includes a feature for tracking book loans. Each book has a loan period, and your system should be able to identify overdue books.\n\n### Task\nWrite a function `get_overdue_books` that takes in a list of diction...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5629, "level": 1, "question": "### Problem Statement\nYou are developing a library management system that includes a feature for tracking book loans. Each book has a loan period, and your system should be able to identify overdue books.\n\n### Task\nWrite a function `get_overdue_boo...
def maxGold(n, gold): if n == 1: return gold[0] elif n == 2: return max(gold[0], gold[1]) else: prev_prev = gold[0] prev = max(gold[0], gold[1]) for i in range(2, n): current = max(prev, prev_prev + gold[i]) prev_prev, prev = prev, current ...
simplelr_Taco
[ { "content": "Question:\nPhilip is playing a game where he has to collect as much gold as possible from a series of gold mines. There are N gold mines in a row, and each mine has a certain amount of gold in it. However, there's a catch: when Philip mines from a particular gold mine, he cannot mine from any of t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5630, "level": 1, "question": "Philip is playing a game where he has to collect as much gold as possible from a series of gold mines. There are N gold mines in a row, and each mine has a certain amount of gold in it. However, there's a catch: when Philip mines from a particular gold...
def judge_circle(moves): dict_moves = { 'U': 0, 'D': 0, 'R': 0, 'L': 0 } for char in moves: dict_moves[char] += 1 return dict_moves['L'] == dict_moves['R'] and dict_moves['U'] == dict_moves['D'] # Test Cases print(judge_circle("UD")) # Expected: True prin...
simplelr_Data_Structure
[ { "content": "Question:\n### Question\n\n#### Scenario:\nYou are a software developer tasked with writing a function to analyze sequences of moves made by a robot in a 2D plane to determine if it returns to its starting position. Each sequence describes the moves as a string of characters, and you need to ensur...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5631, "level": 1, "question": "### Question\n\n#### Scenario:\nYou are a software developer tasked with writing a function to analyze sequences of moves made by a robot in a 2D plane to determine if it returns to its starting position. Each sequence describes the moves as a string o...
def removeKdigits(s: str, k: int) -> str: stack = [] for digit in s: while stack and stack[-1] > digit and k > 0: stack.pop() k -= 1 stack.append(digit) if k > 0: stack = stack[:-k] if len(stack) > k else [] result = ''.join(stack).lstrip('0') return r...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` that consists of digits only and an integer `k`. You can remove `k` digits from the string so that the resulting string is the smallest possible. Return the resulting string as the smallest possible number.\n\n### Example:\n- Input: `s = \"1432219\"`, `k = 3`\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5632, "level": 1, "question": "You are given a string `s` that consists of digits only and an integer `k`. You can remove `k` digits from the string so that the resulting string is the smallest possible. Return the resulting string as the smallest possible number.\n\n### Example:\n-...
def sum_of_squares_of_evens(nums): return sum(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, nums)))
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of integers and returns the sum of the squares of the even numbers in the list. Use a lambda function inside the map function to square the even numbers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5633, "level": 1, "question": "Write a Python function that takes a list of integers and returns the sum of the squares of the even numbers in the list. Use a lambda function inside the map function to square the even numbers.", "split": "train" }
import quopri import re def process_qp_file(input_file_path: str, output_file_path: str) -> None: # Read the input file in binary mode with open(input_file_path, 'rb') as f: data = f.read() # Decode the quoted-printable encoded bytes decoded_bytes = quopri.decodestring(data) # Dec...
simplelr_Docs
[ { "content": "Question:\n### Quoted-Printable Data Handling\n\n#### Objective:\nYou are tasked with developing a function to read a quoted-printable encoded text file, decode it, modify the content, and then encode it back to a quoted-printable encoded text file.\n\n#### Requirements:\n1. **Read and decode a qu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5634, "level": 1, "question": "### Quoted-Printable Data Handling\n\n#### Objective:\nYou are tasked with developing a function to read a quoted-printable encoded text file, decode it, modify the content, and then encode it back to a quoted-printable encoded text file.\n\n#### Requi...
def remove_duplicates(sorted_list): if not sorted_list: return [] unique = [sorted_list[0]] for element in sorted_list[1:]: if element != unique[-1]: unique.append(element) return unique
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that efficiently removes duplicate elements from a sorted list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5635, "level": 1, "question": "Create a Python function that efficiently removes duplicate elements from a sorted list.", "split": "train" }
import pandas as pd def display_selected_columns(csv_file_path: str, columns: list) -> pd.DataFrame: """ Filters and displays specific columns from a CSV file. Args: csv_file_path (str): The path to the CSV file. columns (list): A list of column names to be displayed. Returns: ...
simplelr_Filter
[ { "content": "Question:\nI'm trying to create a Python script that uses pandas to filter and display specific columns from a CSV file. I want the script to be flexible, allowing for the selection of any number of columns to be displayed. Can you help me construct a function that accepts a list of column names a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5636, "level": 1, "question": "I'm trying to create a Python script that uses pandas to filter and display specific columns from a CSV file. I want the script to be flexible, allowing for the selection of any number of columns to be displayed. Can you help me construct a function th...
def product_of_list(nums): if not nums: return 1 product = 1 for num in nums: product *= num return product
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of integers as input and returns the product of the numbers in the list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5637, "level": 1, "question": "Write a Python function that takes a list of integers as input and returns the product of the numbers in the list.", "split": "train" }
def matrix_multiply(A: list, B: list) -> list: # Check if A is a valid matrix a_rows = len(A) a_cols = 0 if a_rows > 0: a_cols = len(A[0]) for row in A: if len(row) != a_cols: raise ValueError("Matrix A has inconsistent row lengths.") # Check if B is ...
simplelr_Data_Structure
[ { "content": "Question:\nYou are provided with two two-dimensional matrices. Write a function to compute their product. If the matrices are not compatible for multiplication, the function should raise an exception.\n\n### Function Signature:\n```python\ndef matrix_multiply(A: list, B: list) -> list:\n pass\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5638, "level": 1, "question": "You are provided with two two-dimensional matrices. Write a function to compute their product. If the matrices are not compatible for multiplication, the function should raise an exception.\n\n### Function Signature:\n```python\ndef matrix_multiply(A: ...
def optimized_bellman_ford(num_vertices, edges, source): """ Determines single-source shortest paths from the given source vertex to all other vertices. Parameters: - num_vertices (int): The total number of vertices in the graph. - edges (List[Tuple[int, int, int]]): The list of edges i...
simplelr_Data_Structure
[ { "content": "Question:\n### Coding Challenge: Optimizing the Bellman-Ford Algorithm\n\n#### Problem Statement\nYou are given a directed weighted graph represented as an edge list. Each edge is represented as a triplet `(u, v, w)` where `u` is the start vertex, `v` is the end vertex, and `w` is the weight of th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5639, "level": 1, "question": "### Coding Challenge: Optimizing the Bellman-Ford Algorithm\n\n#### Problem Statement\nYou are given a directed weighted graph represented as an edge list. Each edge is represented as a triplet `(u, v, w)` where `u` is the start vertex, `v` is the end ...
def next_char(s): result = [] for c in s: if c.isalpha(): if c == 'z': result.append('a') elif c == 'Z': result.append('A') else: result.append(chr(ord(c) + 1)) else: result.append(c) return ''.jo...
simplelr_Apps
[ { "content": "Question:\nWrite a function that takes a string of English letters and returns another string where each character is replaced by the next character in the alphabet. If the character is 'z' or 'Z', it should be wrapped around to 'a' or 'A' respectively. Non-alphabetic characters should remain unch...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5640, "level": 1, "question": "Write a function that takes a string of English letters and returns another string where each character is replaced by the next character in the alphabet. If the character is 'z' or 'Z', it should be wrapped around to 'a' or 'A' respectively. Non-alpha...
import seaborn.objects as so from seaborn import load_dataset def visualize_penguins(): # Load the penguins dataset penguins = load_dataset("penguins") # Dot plot with error bars plot1 = ( so.Plot(penguins, x="body_mass_g", y="species", color="sex") .add(so.Dot(), so.Agg(), so.Dodge())...
simplelr_Docs
[ { "content": "Question:\n#### Objective\nDemonstrate your understanding of the seaborn package's capabilities for data visualization and statistical representation by solving the following problem.\n\n#### Question\nYou are given the seaborn `penguins` dataset. Your task is to create a series of plots that prov...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5641, "level": 1, "question": "#### Objective\nDemonstrate your understanding of the seaborn package's capabilities for data visualization and statistical representation by solving the following problem.\n\n#### Question\nYou are given the seaborn `penguins` dataset. Your task is to...
def count_overlapping_occurrences(main, sub): sub_len = len(sub) main_len = len(main) if sub_len == 0 or sub_len > main_len: return 0 count = 0 for i in range(main_len - sub_len + 1): if main[i:i + sub_len] == sub: count += 1 return count
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to count the number of occurrences of a substring in a string. You should count overlapping occurrences as well. For example, \"aaa\" should return 2 for the string \"aaaa\".\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5642, "level": 1, "question": "Write a python function to count the number of occurrences of a substring in a string. You should count overlapping occurrences as well. For example, \"aaa\" should return 2 for the string \"aaaa\".", "split": "train" }
def hasRepeats(lst): return len(lst) != len(set(lst))
simplelr_Filter
[ { "content": "Question:\nWrite a function 'hasRepeats' that checks if a list has two of the same elements.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5643, "level": 1, "question": "Write a function 'hasRepeats' that checks if a list has two of the same elements.", "split": "train" }
def median_of_three(a, b, c): return a + b + c - max(a, b, c) - min(a, b, c)
simplelr_Filter
[ { "content": "Question:\nDebug the following code for finding the median of three numbers, but you are not allowed to use any conditional statements (if, elif, else) or any comparison operators (>, <, ==).\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5644, "level": 1, "question": "Debug the following code for finding the median of three numbers, but you are not allowed to use any conditional statements (if, elif, else) or any comparison operators (>, <, ==).", "split": "train" }
def generate_acronym(phrase: str) -> str: words = phrase.split() acronym = [] for word in words: if word: # Ensure the word is not empty acronym.append(word[0].upper()) return ''.join(acronym)
simplelr_Code_Contests
[ { "content": "Question:\nYou are working on a text analysis tool that needs to understand and generate acronyms for technical terms. An acronym is a shorter version of a phrase, where each letter in the acronym stands for the initial letter of one of the words in the phrase. For example, \"Natural Language Proc...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5645, "level": 1, "question": "You are working on a text analysis tool that needs to understand and generate acronyms for technical terms. An acronym is a shorter version of a phrase, where each letter in the acronym stands for the initial letter of one of the words in the phrase. F...
def specialSort(arr, N, K): # Separate the elements into two lists: divisible and non-divisible by K divisible = [] non_divisible = [] for num in arr: if num % K == 0: divisible.append(num) else: non_divisible.append(num) # Concatenate the two lists and update...
simplelr_Taco
[ { "content": "Question:\nGeek loves sorting algorithms. He recently came across a unique sorting challenge. He needs to sort a given array of integers in a special manner: all elements that are divisible by a given number K should appear at the start of the array, and the remaining elements should follow. Both ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5646, "level": 1, "question": "Geek loves sorting algorithms. He recently came across a unique sorting challenge. He needs to sort a given array of integers in a special manner: all elements that are divisible by a given number K should appear at the start of the array, and the rema...
def find_missing_number(arr): n = len(arr) expected_sum = n * (n + 1) // 2 actual_sum = sum(arr) return expected_sum - actual_sum
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the missing number in an array of integers. The array contains numbers from 0 to n with exactly one number missing. The function should ideally be efficient and use minimal time and space complexity.\nAnswer:\nLet's think step by step.\n", "role": "us...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5647, "level": 1, "question": "Write a python function to find the missing number in an array of integers. The array contains numbers from 0 to n with exactly one number missing. The function should ideally be efficient and use minimal time and space complexity.", "split": "train"...
def remove_occurrences(y, x): result = [] for element in y: if element != x: result.append(element) return result
simplelr_Filter
[ { "content": "Question:\nGenerate a python code to remove all the occurrences of the element x from a list y, while maintaining the original order of the remaining elements in the list. The solution should have a time complexity of O(n) and should not use any built-in functions or libraries to achieve the resul...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5648, "level": 1, "question": "Generate a python code to remove all the occurrences of the element x from a list y, while maintaining the original order of the remaining elements in the list. The solution should have a time complexity of O(n) and should not use any built-in function...
def double_characters(s): return ''.join([c * 2 for c in s])
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in a string and returns a new string with each character doubled. For example, the string \"hello\" should become \"hheelllloo\".\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5649, "level": 1, "question": "Create a function that takes in a string and returns a new string with each character doubled. For example, the string \"hello\" should become \"hheelllloo\".", "split": "train" }
def operate(item, value1, value2): operations = { 'A': lambda a, b: a + b, 'B': lambda a, b: a - b, 'C': lambda a, b: a * b } if item in operations: return operations[item](value1, value2) else: raise ValueError("Invalid item type")
simplelr_Filter
[ { "content": "Question:\nI have 3 types of items: A, B, and C. I need to write a code that operates on these items such that for each type, it performs a different set of operations. How would I do this in Python?\n\nYou could provide an example where type A does addition, type B does subtraction, and type C do...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5650, "level": 1, "question": "I have 3 types of items: A, B, and C. I need to write a code that operates on these items such that for each type, it performs a different set of operations. How would I do this in Python?\n\nYou could provide an example where type A does addition, typ...
import fnmatch def filter_and_count_filenames(filenames: list, pattern: str) -> dict: filtered = fnmatch.filter(filenames, pattern) extension_counts = {} for filename in filtered: extension = '.' + filename.split('.')[-1] extension_counts[extension] = extension_counts.get(extension, 0) + 1 ...
simplelr_Docs
[ { "content": "Question:\n### Filename Pattern Filtering and Counting\n\n#### Problem Statement\n\nYou are tasked with writing a Python function to filter a list of filenames based on a given pattern and to count the occurrences of each file extension in the filtered results. This will demonstrate your understan...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5651, "level": 1, "question": "### Filename Pattern Filtering and Counting\n\n#### Problem Statement\n\nYou are tasked with writing a Python function to filter a list of filenames based on a given pattern and to count the occurrences of each file extension in the filtered results. T...
def longest_subsequence(nums, d): if not nums: return 0 dp = {} max_len = 0 for num in nums: prev = num - d current = dp.get(prev, 0) + 1 dp[num] = max(dp.get(num, 0), current) if dp[num] > max_len: max_len = dp[num] return max_len
simplelr_Leetcode
[ { "content": "Question:\nGiven a `0-indexed` integer array `nums` containing `n` integers, return the length of the longest subsequence such that the difference between consecutive elements is exactly `d`. A subsequence is a sequence derived by deleting some or none of the elements in the array without changing...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5652, "level": 1, "question": "Given a `0-indexed` integer array `nums` containing `n` integers, return the length of the longest subsequence such that the difference between consecutive elements is exactly `d`. A subsequence is a sequence derived by deleting some or none of the ele...
def get_indices(lst, elem): indices = [] for i in range(len(lst)): if lst[i] == elem: indices.append(i) return indices
simplelr_Filter
[ { "content": "Question:\nGenerate a Python function to get the indices of all occurrences of a specified element in a list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5653, "level": 1, "question": "Generate a Python function to get the indices of all occurrences of a specified element in a list.", "split": "train" }
def max_subarray_sum(nums): if not nums: return [] if max(nums) < 0: return [] max_so_far = current_max = nums[0] max_start = max_end = current_start = current_end = 0 for i in range(1, len(nums)): if current_max + nums[i] < nums[i]: current_max = nums[i...
simplelr_Filter
[ { "content": "Question:\nGiven a list of integers, write a function to calculate the maximum subarray sum using Kadane's algorithm. However, there is a twist. You need to modify the original algorithm to also return the starting and ending indices of the subarray that gives the maximum sum. Additionally, your f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5654, "level": 1, "question": "Given a list of integers, write a function to calculate the maximum subarray sum using Kadane's algorithm. However, there is a twist. You need to modify the original algorithm to also return the starting and ending indices of the subarray that gives th...
def prime_factors(n: int) -> list: if n < 2: return [] factors = [] # Handle the factor of 2 while n % 2 == 0: factors.append(2) n = n // 2 # Now n must be odd, start from 3 i = 3 while i * i <= n: while n % i == 0: factors.append(i) n ...
simplelr_Codeforces
[ { "content": "Question:\nImplement a function that takes an integer `n` and returns a list of all prime factors of `n`. The prime factors should be in ascending order. If `n` is less than 2, return an empty list.\n\nFor example, given `n = 28`, the function should return `[2, 2, 7]` because 28 = 2 * 2 * 7. \n\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5655, "level": 1, "question": "Implement a function that takes an integer `n` and returns a list of all prime factors of `n`. The prime factors should be in ascending order. If `n` is less than 2, return an empty list.\n\nFor example, given `n = 28`, the function should return `[2, ...
def max_subarray_sum(arr): if not arr: return 0 # As per problem statement, arr is non-empty, but handling empty case. max_so_far = current_max = arr[0] for num in arr[1:]: current_max = max(num, current_max + num) max_so_far = max(max_so_far, current_max) return max_so_far
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `arr`, your task is to find and return _the maximum possible sum of any non-empty subarray (contiguous sequence of elements)_ of `arr`. A subarray is defined as a contiguous subsequence of the array. \n\nNote: Your solution must have a linear runtime complexit...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5656, "level": 1, "question": "Given an array of integers `arr`, your task is to find and return _the maximum possible sum of any non-empty subarray (contiguous sequence of elements)_ of `arr`. A subarray is defined as a contiguous subsequence of the array. \n\nNote: Your solution m...
from collections import deque def shortest_path_to_exit(matrix): if not matrix or not matrix[0]: return -1 rows = len(matrix) cols = len(matrix[0]) start_row, start_col = 0, 0 if matrix[start_row][start_col] == 'E': return 1 if matrix[start_row][start_col] == '1': re...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a 2D grid `matrix` of characters where each character can be one of `'0'`, `'1'`, or `'E'`. The grid represents a field where `'0'` is an empty cell, `'1'` is an obstacle, and `'E'` is an exit. You start at the top-left corner of the grid (position `(0, 0)`). You can move ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5657, "level": 1, "question": "You are given a 2D grid `matrix` of characters where each character can be one of `'0'`, `'1'`, or `'E'`. The grid represents a field where `'0'` is an empty cell, `'1'` is an obstacle, and `'E'` is an exit. You start at the top-left corner of the grid...
def int_to_string(number: int) -> str: return str(number)
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python function to convert an integer to a string?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5658, "level": 1, "question": "Can you provide a Python function to convert an integer to a string?", "split": "train" }
# Initialize the global cache with the first Fibonacci number _fib_cache = [0] def fibonacci(n): """ Generates the first 'n' numbers of the Fibonacci sequence using dynamic programming and caching. Args: n (int): The number of Fibonacci numbers to generate. Returns: list: A list conta...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to generate the first n numbers of the Fibonacci sequence. The function should be efficient and handle large values of n. Use dynamic programming to avoid recalculating values. Additionally, implement a caching mechanism to store previously computed values for fu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5659, "level": 1, "question": "Write a Python function to generate the first n numbers of the Fibonacci sequence. The function should be efficient and handle large values of n. Use dynamic programming to avoid recalculating values. Additionally, implement a caching mechanism to stor...
def group_by_elements(tuple_list): result = {} for t in tuple_list: for elem in t: if elem not in result: result[elem] = [] result[elem].append(t) return result
simplelr_Filter
[ { "content": "Question:\nSo I think I understand how to approach this problem but I need a little guidance on the implementation details. \n\nI am trying to write a function that takes in a list of tuples and returns a dictionary where each key is a unique element from the list of tuples and each value is a lis...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5660, "level": 1, "question": "So I think I understand how to approach this problem but I need a little guidance on the implementation details. \n\nI am trying to write a function that takes in a list of tuples and returns a dictionary where each key is a unique element from the lis...
def unique_paths_with_obstacles(grid): n = len(grid) if n == 0: return 0 if grid[0][0] == 1 or grid[n-1][n-1] == 1: return 0 dp = [[0] * n for _ in range(n)] dp[0][0] = 1 for i in range(n): for j in range(n): if i == 0 and j == 0: continue ...
simplelr_Filter
[ { "content": "Question:\nYou have a square grid of size n x n and there are some obstacles placed randomly in the grid. You need to find the number of ways to reach the bottom right corner (n, n) starting from the top left corner (1, 1) while avoiding the obstacles. \n\nThe grid is represented as a 2D array whe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5661, "level": 1, "question": "You have a square grid of size n x n and there are some obstacles placed randomly in the grid. You need to find the number of ways to reach the bottom right corner (n, n) starting from the top left corner (1, 1) while avoiding the obstacles. \n\nThe gr...
def account_balance(transactions): balance = 0.0 for transaction in transactions: parts = transaction.split() action = parts[0] amount = float(parts[1]) if action == 'D': balance += amount else: balance -= amount return int(balance) if balance....
simplelr_Taco
[ { "content": "Question:\nYou are a software engineer working on a project to develop a simplified account management system for a bank. The bank needs to be able to track deposits and withdrawals made to a customer's account over a period of time.\n\nWrite a function `account_balance(transactions)` that takes a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5662, "level": 1, "question": "You are a software engineer working on a project to develop a simplified account management system for a bank. The bank needs to be able to track deposits and withdrawals made to a customer's account over a period of time.\n\nWrite a function `account_...
def find_missing_number(nums: list) -> int: # Check if the input is a list if not isinstance(nums, list): raise ValueError("Input must be a list of integers.") # Check each element is an integer for num in nums: if not isinstance(num, int): raise ValueError("Input must b...
simplelr_Algorithm
[ { "content": "Question:\n## Title: Find the Missing Number in a Consecutive Integer Sequence\n\n### Description\nYou are to write a function that finds the missing number from a given list of `n` consecutive integers, starting from `1` up to `n+1`. The input list will contain `n` integers, and exactly one of th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5663, "level": 1, "question": "## Title: Find the Missing Number in a Consecutive Integer Sequence\n\n### Description\nYou are to write a function that finds the missing number from a given list of `n` consecutive integers, starting from `1` up to `n+1`. The input list will contain ...
def reverse_list(lst): left = 0 right = len(lst) - 1 while left < right: lst[left], lst[right] = lst[right], lst[left] left += 1 right -= 1 return lst
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to reverse a list without using any additional data structures. The function should achieve this by swapping elements in place.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5664, "level": 1, "question": "Write a python function to reverse a list without using any additional data structures. The function should achieve this by swapping elements in place.", "split": "train" }
def running_sum(arr): current_sum = 0 result = [] for num in arr: current_sum += num result.append(current_sum) return result
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers, return a new array where each element is the sum of itself and all the previous elements in the original array. This is known as the \"running sum\" of the input array.\n\nFor example:\n```\nInput: [1, 2, 3, 4]\nOutput: [1, 3, 6, 10]\n\nExplanation:\nrunningS...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5665, "level": 1, "question": "Given an array of integers, return a new array where each element is the sum of itself and all the previous elements in the original array. This is known as the \"running sum\" of the input array.\n\nFor example:\n```\nInput: [1, 2, 3, 4]\nOutput: [1, ...
def find_key_in_dict(d, k): return d.get(k)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function `find_key_in_dict` that takes two arguments: a dictionary `d` and a key `k`. The function should return the value associated with the key `k` in the dictionary `d` if the key is present, and `None` if the key is not found.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5666, "level": 1, "question": "Write a Python function `find_key_in_dict` that takes two arguments: a dictionary `d` and a key `k`. The function should return the value associated with the key `k` in the dictionary `d` if the key is present, and `None` if the key is not found.", "...
def product_of_primes(n: int) -> int: if n < 2: return 1 # Though, according to the problem statement, n >= 2 # Initialize the sieve sieve = [True] * (n + 1) sieve[0], sieve[1] = False, False # Sieve of Eratosthenes algorithm for i in range(2, int(n ** 0.5) + 1): if si...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Problem Statement:\nYou are provided with a function `product_of_primes` which is supposed to calculate the product of all prime numbers up to and including a given number `n`. Your task is to implement this function efficiently. \n\n#### Input:\n-...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5667, "level": 1, "question": "### Coding Assessment Question\n\n#### Problem Statement:\nYou are provided with a function `product_of_primes` which is supposed to calculate the product of all prime numbers up to and including a given number `n`. Your task is to implement this funct...
def factorial(n): result = 1 for i in range(1, n + 1): result *= i return result
simplelr_Filter
[ { "content": "Question:\nHere's a recursive function that calculates the factorial of a number:\n```\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n```\nHowever, the function has a problem: it can cause a \"RecursionError: maximum recursion depth exceeded\" f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5668, "level": 1, "question": "Here's a recursive function that calculates the factorial of a number:\n```\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n```\nHowever, the function has a problem: it can cause a \"RecursionError: m...
from typing import List def all_books_available(bookshelf: List[str], interested_books: List[str]) -> bool: shelf_set = set(bookshelf) interested_set = set(interested_books) return interested_set.issubset(shelf_set)
simplelr_Code_Contests
[ { "content": "Question:\nWhen you are allocated a room for a programming competition, you have access to a bookshelf with M books. You have a list of k books you are particularly interested in reading during your free time. You want to ensure you have these books before anyone else takes them.\n\nGiven two list...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5669, "level": 1, "question": "When you are allocated a room for a programming competition, you have access to a bookshelf with M books. You have a list of k books you are particularly interested in reading during your free time. You want to ensure you have these books before anyone...
def hotelPicker(hotelsStayed, hotelsRecommended): for hotel in hotelsRecommended: if hotel not in hotelsStayed: return hotel return 'No new hotels available!'
simplelr_Apps
[ { "content": "Question:\nLucy is planning to attend a symposium on emerging technologies. To make her trip more enjoyable, she prefers to stay at hotels that she hasn't stayed at before. The symposium's organizers have a list of recommended hotels in order of their proximity to the symposium venue.\n\nWrite a f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5670, "level": 1, "question": "Lucy is planning to attend a symposium on emerging technologies. To make her trip more enjoyable, she prefers to stay at hotels that she hasn't stayed at before. The symposium's organizers have a list of recommended hotels in order of their proximity t...
def calculate_tax(income: float, tax_brackets: list[tuple[float, float]]) -> float: total_tax = 0.0 prev_limit = 0.0 last_rate = 0.0 for bracket in tax_brackets: current_limit, rate = bracket if income <= prev_limit: break current_taxable = min(current_limit, income) ...
simplelr_Algorithm
[ { "content": "Question:\n### Progressive Tax Calculation\n\nYou are required to implement a function `calculate_tax()` that computes the tax owed based on a progressive tax system. The tax brackets and corresponding rates are given as inputs.\n\n### Problem Statement\n\nGiven a list of tuples representing tax b...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5671, "level": 1, "question": "### Progressive Tax Calculation\n\nYou are required to implement a function `calculate_tax()` that computes the tax owed based on a progressive tax system. The tax brackets and corresponding rates are given as inputs.\n\n### Problem Statement\n\nGiven ...
def dfs_traversal(graph: dict, start: str) -> list: stack = [start] visited = set() traversal_order = [] while stack: node = stack.pop() if node not in visited: visited.add(node) traversal_order.append(node) for neighbor in reversed(graph[node]): ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement: Graph Traversal Using Depth-First Search (DFS)\n\n#### Context\nYou are tasked with implementing the depth-first search (DFS) algorithm to traverse a graph from a given starting node. The algorithm should be able to handle both connected and disconnected graphs, a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5672, "level": 1, "question": "### Problem Statement: Graph Traversal Using Depth-First Search (DFS)\n\n#### Context\nYou are tasked with implementing the depth-first search (DFS) algorithm to traverse a graph from a given starting node. The algorithm should be able to handle both c...
def length_of_longest_substring(s): if not s: return 0 char_index_map = {} max_len = 0 left = 0 for right in range(len(s)): char = s[right] if char in char_index_map and char_index_map[char] >= left: left = char_index_map[char] + 1 char_index_map[char] = r...
simplelr_Taco
[ { "content": "Question:\nCreate a function that receives a string as input and returns the length of the longest substring without repeating characters. Your solution should iterate through the string only once, in linear time complexity.\n\nSAMPLE INPUT\nabcabcbb\nbbbbb\npwwkew\n\nSAMPLE OUTPUT\n3\n1\n3\n\nExp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5673, "level": 1, "question": "Create a function that receives a string as input and returns the length of the longest substring without repeating characters. Your solution should iterate through the string only once, in linear time complexity.\n\nSAMPLE INPUT\nabcabcbb\nbbbbb\npwwk...
def buddyStrings(s: str, goal: str) -> bool: if len(s) != len(goal): return False if s == goal: return len(set(s)) < len(s) else: diffs = [] for i in range(len(s)): if s[i] != goal[i]: diffs.append(i) if len(diffs) > 2: ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given two strings, `s` and `goal`. Your task is to determine if you can swap two letters in string `s` such that the resulting string matches the string `goal`. If it is possible to achieve this by swapping exactly two letters once, return `true`; otherwise, return `false`.\n\nI...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5674, "level": 1, "question": "You are given two strings, `s` and `goal`. Your task is to determine if you can swap two letters in string `s` such that the resulting string matches the string `goal`. If it is possible to achieve this by swapping exactly two letters once, return `tru...
import torch def special_operations(tensor: torch.Tensor) -> torch.Tensor: # Step 1: Compute the natural logarithm of the complementary error function for each element erfc_values = torch.special.erfc(tensor) a = torch.log(erfc_values) # Step 2: Apply log-sum-exp across each row and keep the dimen...
simplelr_Docs
[ { "content": "Question:\n**Special Mathematical Operations on Tensor Data using PyTorch**\n\nPyTorch provides a variety of special mathematical functions in the `torch.special` module, which can be used for complex numerical computations. In this task, you will demonstrate your understanding of these functions ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5675, "level": 1, "question": "**Special Mathematical Operations on Tensor Data using PyTorch**\n\nPyTorch provides a variety of special mathematical functions in the `torch.special` module, which can be used for complex numerical computations. In this task, you will demonstrate you...
def character_frequency(s): """ This function takes a string, calculates the frequency of each alphanumeric character (ignoring case and non-alphanumeric characters), sorts them by frequency in descending order, and returns the result as a dictionary. The function also prints the frequency table. P...
simplelr_Filter
[ { "content": "Question:\nCreate a function in Python that takes a string and prints the frequency table of all its alphanumeric characters, excluding any special characters or whitespaces. The output should be sorted in descending order of frequency. The function should also ignore the case of the characters. T...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5676, "level": 1, "question": "Create a function in Python that takes a string and prints the frequency table of all its alphanumeric characters, excluding any special characters or whitespaces. The output should be sorted in descending order of frequency. The function should also i...
def find_max_index(lst): return lst.index(max(lst))
simplelr_Filter
[ { "content": "Question:\nI have a list of integers, and I want to find the index of the first occurrence of the maximum value in the list. If there are multiple maximum values, it should return the index of the first one. \n\nFor example, if the input list is `[4, 2, 9, 6, 5, 1, 8, 3, 7]`, the output should be ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5677, "level": 1, "question": "I have a list of integers, and I want to find the index of the first occurrence of the maximum value in the list. If there are multiple maximum values, it should return the index of the first one. \n\nFor example, if the input list is `[4, 2, 9, 6, 5, ...
def maxCommitsInInterval(commits, n, m): if n == 0: return 0 commits.sort() max_commits = 0 left = 0 for right in range(n): while commits[right] - commits[left] > m: left += 1 current = right - left + 1 if current > max_commits: max_commits = c...
simplelr_Taco
[ { "content": "Question:\nA company wants to monitor the performance of different software teams based on their code commit frequencies. Given a list of integers representing the commit times (in minutes from the start of the monitoring period) for various commits made by a team, determine the maximum number of ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5678, "level": 1, "question": "A company wants to monitor the performance of different software teams based on their code commit frequencies. Given a list of integers representing the commit times (in minutes from the start of the monitoring period) for various commits made by a tea...
def generate_leaderboard( players: dict, bonuses: dict ) -> list: """ Generate a sorted leaderboard based on initial and bonus scores. Parameters: - players (dict): Dictionary with player names as keys and their initial scores as values. - bonuses (dict): Dictionary with player names as...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n**Scenario**:\nAs a game developer, you need to generate a leaderboard for a multiplayer online game. Each player has a score, and bonus points may be awarded based on certain milestones achieved during the game.\n\n**Task**:\nImplement a Python functio...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5679, "level": 1, "question": "### Coding Assessment Question\n\n**Scenario**:\nAs a game developer, you need to generate a leaderboard for a multiplayer online game. Each player has a score, and bonus points may be awarded based on certain milestones achieved during the game.\n\n**...
def count_mixed_case_strings(lst): count = 0 for s in lst: has_lower = any(c.islower() for c in s) has_upper = any(c.isupper() for c in s) if has_lower and has_upper: count += 1 return count
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in a list of strings, and counts how many strings have at least one lowercase letter and one uppercase letter.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5680, "level": 1, "question": "Create a function that takes in a list of strings, and counts how many strings have at least one lowercase letter and one uppercase letter.", "split": "train" }
def maxProductOfThree(nums): nums.sort() n = len(nums) candidate1 = nums[-1] * nums[-2] * nums[-3] candidate2 = nums[0] * nums[1] * nums[-1] return max(candidate1, candidate2)
simplelr_Taco
[ { "content": "Question:\nGiven an integer array, find the maximum possible product of three numbers in the array.\n\nWrite a function `maxProductOfThree` that takes an array `nums` and returns an integer representing the maximum product of any three numbers in the array.\n\n### Input\n- An integer array `nums` ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5681, "level": 1, "question": "Given an integer array, find the maximum possible product of three numbers in the array.\n\nWrite a function `maxProductOfThree` that takes an array `nums` and returns an integer representing the maximum product of any three numbers in the array.\n\n##...
def can_be_divided_in_k_subsequences(s, k): piles = [] for c in s: added = False for i in range(len(piles)): if piles[i] <= c: piles[i] = c added = True break if not added: piles.append(c) minimal_k = len(piles) ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` and an integer `k`. The string `s` consists of lowercase English letters. Your task is to divide string `s` into exactly `k` non-empty subsequences such that each subsequence is sorted in non-decreasing order. \n\nReturn `true` if it is possible to split the s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5682, "level": 1, "question": "You are given a string `s` and an integer `k`. The string `s` consists of lowercase English letters. Your task is to divide string `s` into exactly `k` non-empty subsequences such that each subsequence is sorted in non-decreasing order. \n\nReturn `tru...
def optimized_shell_sort(arr): n = len(arr) if n <= 1: return arr gaps = [] h = 1 while h < n: gaps.append(h) h = h * 4 + 1 gaps = gaps[::-1] for gap in gaps: for i in range(gap, n): j = i while j >= gap: ...
simplelr_Data_Structure
[ { "content": "Question:\n### Shell Sort Implementation Task\n\nShell Sort is a significant step above insertion sort and bubble sort, particularly for medium-sized datasets. Given its relative complexity and the effect of gap sequences on performance, implementing and optimizing Shell Sort can be a valuable exe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5683, "level": 1, "question": "### Shell Sort Implementation Task\n\nShell Sort is a significant step above insertion sort and bubble sort, particularly for medium-sized datasets. Given its relative complexity and the effect of gap sequences on performance, implementing and optimizi...
def is_match(s: str, p: str) -> bool: n, m = len(s), len(p) dp = [[False] * (m + 1) for _ in range(n + 1)] dp[0][0] = True for i in range(n + 1): for j in range(m + 1): if i == 0 and j == 0: dp[i][j] = True continue if j == 0: ...
simplelr_Data_Structure
[ { "content": "Question:\n### Regular Expression Matching\n\n#### Problem Statement\nWrite a function `is_match(s: str, p: str) -> bool` that implements a regular expression matching with support for '.' and '*'. The matching function should match the entire input string `s` against the pattern `p`.\n\n#### Spec...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5684, "level": 1, "question": "### Regular Expression Matching\n\n#### Problem Statement\nWrite a function `is_match(s: str, p: str) -> bool` that implements a regular expression matching with support for '.' and '*'. The matching function should match the entire input string `s` ag...
def longestConsecutiveSubsequence(nums): if not nums: return 0 unique = list(set(nums)) unique.sort() max_len = 1 current_len = 1 for i in range(1, len(unique)): if unique[i] == unique[i-1] + 1: current_len += 1 if current_len > max_len: ma...
simplelr_Leetcode
[ { "content": "Question:\nGiven a list of `n` integers, write a function to find the length of the longest subsequence such that all elements of the subsequence are consecutive integers. A consecutive sequence is defined as a sequence where the difference between the maximum and minimum element is equal to the n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5685, "level": 1, "question": "Given a list of `n` integers, write a function to find the length of the longest subsequence such that all elements of the subsequence are consecutive integers. A consecutive sequence is defined as a sequence where the difference between the maximum an...
def has_unique_characters(s): check = [False] * 26 for c in s: index = ord(c) - ord('a') if check[index]: return False check[index] = True return True
simplelr_Filter
[ { "content": "Question:\nWrite a Python program that goes through a given string and checks if the string has all unique characters. It should return True if all characters are unique and False if there are any duplicates. Additionally, optimize the program to run in O(n) time complexity and use constant O(1) e...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5686, "level": 1, "question": "Write a Python program that goes through a given string and checks if the string has all unique characters. It should return True if all characters are unique and False if there are any duplicates. Additionally, optimize the program to run in O(n) time...
from typing import List def transpose_matrix_diagonal(matrix: List[List[int]]) -> List[List[int]]: n = len(matrix) for i in range(n): for j in range(i + 1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] return matrix
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are required to implement a function `transpose_matrix_diagonal` that takes a square matrix and returns the matrix obtained by transposing it along its diagonal. In a diagonal transpose, the element at position `(i, j)` swaps places with the element at posit...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5687, "level": 1, "question": "### Problem Statement\n\nYou are required to implement a function `transpose_matrix_diagonal` that takes a square matrix and returns the matrix obtained by transposing it along its diagonal. In a diagonal transpose, the element at position `(i, j)` swa...
def initials(name): parts = name.split() return ''.join([part[0].upper() for part in parts])
simplelr_Filter
[ { "content": "Question:\nYou've been tasked with creating a function `initials` that takes a person's full name as input and returns the initials of the person. The input will be a string containing the person's first, middle, and last names, and each name will be separated by a space. Assume that the person ha...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5688, "level": 1, "question": "You've been tasked with creating a function `initials` that takes a person's full name as input and returns the initials of the person. The input will be a string containing the person's first, middle, and last names, and each name will be separated by...
def organize_grades(students): grade_book = { 'A': [], 'B': [], 'C': [], 'D': [], 'F': [] } for student in students: name, grade = student if grade >= 90: grade_book['A'].append(name) elif grade >= 80: grade_book['B...
simplelr_Evol
[ { "content": "Question:\nWrite a function that organizes a list of tuples representing students and their grades into a dictionary where the keys are the grade categories (A, B, C, D, F) and the values are lists of student names. Each student's grade is evaluated based on the following scale:\n\n- A: 90 - 100\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5689, "level": 1, "question": "Write a function that organizes a list of tuples representing students and their grades into a dictionary where the keys are the grade categories (A, B, C, D, F) and the values are lists of student names. Each student's grade is evaluated based on the ...
def is_permutation(s1: str, s2: str) -> bool: if len(s1) != len(s2): return False count = [0] * 26 for c in s1: count[ord(c) - ord('a')] += 1 for c in s2: count[ord(c) - ord('a')] -= 1 return all(v == 0 for v in count)
simplelr_Algorithm
[ { "content": "Question:\n### Coding Question: String Permutation Check\n\n#### Context:\nGiven two strings, determining if one is a permutation of the other is a common problem in programming. This involves checking if one string can be rearranged to form the other. This concept is often used in problems relate...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5690, "level": 1, "question": "### Coding Question: String Permutation Check\n\n#### Context:\nGiven two strings, determining if one is a permutation of the other is a common problem in programming. This involves checking if one string can be rearranged to form the other. This conce...
from typing import List, Optional def average_monthly_temperature(temperatures: List[Optional[float]]) -> float: valid_temps = [t for t in temperatures if t is not None] if not valid_temps: return 0.0 return sum(valid_temps) / len(valid_temps)
simplelr_Package
[ { "content": "Question:\nYou are required to implement a function that calculates the average monthly temperature from a given set of daily temperature readings. The function should sum the provided temperatures and compute the average, ensuring to handle any potential anomalies in the data such as null or miss...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5691, "level": 1, "question": "You are required to implement a function that calculates the average monthly temperature from a given set of daily temperature readings. The function should sum the provided temperatures and compute the average, ensuring to handle any potential anomali...
from typing import List def elevator_simulator(F: int, requests: List[int]) -> List[str]: current_floor = 1 output = [] for req in requests: if 1 <= req <= F: output.append(f"Starting at Floor {current_floor}") output.append(f"Moving to Floor {req}") current_floo...
simplelr_Taco
[ { "content": "Question:\nImplement a simulator for a basic elevator system in a building. The building has a single elevator that travels between floors to pick up and drop off passengers. Design a program that models the elevator operation based on an input sequence of floor requests.\n\n**Rules and Assumption...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5692, "level": 1, "question": "Implement a simulator for a basic elevator system in a building. The building has a single elevator that travels between floors to pick up and drop off passengers. Design a program that models the elevator operation based on an input sequence of floor ...
def find_first_peak(lst): if len(lst) == 1: return 0 for i in range(len(lst)): if i == 0: if lst[i] > lst[i + 1]: return i elif i == len(lst) - 1: if lst[i] > lst[i - 1]: return i else: if lst[i] > lst[i - 1] and...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to find the index of the first peak element in a list of integers. A peak element is one that is greater than its neighbors. For the elements at the boundaries, we consider only one neighbor. The list may contain multiple peaks; return the index to the first one ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5693, "level": 1, "question": "Write a Python function to find the index of the first peak element in a list of integers. A peak element is one that is greater than its neighbors. For the elements at the boundaries, we consider only one neighbor. The list may contain multiple peaks;...
from collections import Counter from typing import List def find_most_frequent_integer(arr: List[int]) -> int: freq_dict = Counter(arr) current_max = 0 current_min = None for num in freq_dict: count = freq_dict[num] if count > current_max: current_max = count cur...
simplelr_Package
[ { "content": "Question:\nYou are required to implement the function `find_most_frequent_integer(arr)`. This function will identify the integer that appears most frequently in a given list and return it. If there are multiple integers with the same highest frequency, return the smallest one.\n\n#### Function Sig...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5694, "level": 1, "question": "You are required to implement the function `find_most_frequent_integer(arr)`. This function will identify the integer that appears most frequently in a given list and return it. If there are multiple integers with the same highest frequency, return the...
def decode_string(s: str) -> str: stack = [] current_str = '' current_num = 0 for c in s: if c.isdigit(): current_num = current_num * 10 + int(c) elif c == '[': stack.append((current_str, current_num)) current_str = '' current_num = 0 ...
simplelr_Data_Structure
[ { "content": "Question:\n### String Decoding Challenge\n\n#### Context\nIn this task, you are required to implement a function that decodes an encoded string. The encoding follows a specific rule: `k[encoded_string]`, where the `encoded_string` is repeated exactly `k` times. Assume the string is well-formed and...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5695, "level": 1, "question": "### String Decoding Challenge\n\n#### Context\nIn this task, you are required to implement a function that decodes an encoded string. The encoding follows a specific rule: `k[encoded_string]`, where the `encoded_string` is repeated exactly `k` times. A...
def simple_grep(substring, lines): sub_lower = substring.lower() for line in lines: if sub_lower in line.lower(): print(line)
simplelr_Package
[ { "content": "Question:\nYou are required to implement a Python function that mimics a simplified version of the Unix `grep` command. The function, named `simple_grep`, should search for a specified substring in a given list of strings and print all lines that contain the substring. The search should be case-in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5696, "level": 1, "question": "You are required to implement a Python function that mimics a simplified version of the Unix `grep` command. The function, named `simple_grep`, should search for a specified substring in a given list of strings and print all lines that contain the subs...
def is_tautonym(s): words = s.split() if len(words) != 2: return False word1, word2 = words[0].lower(), words[1].lower() return word1 == word2
simplelr_Code_Contests
[ { "content": "Question:\nGiven a list of space-separated words, determine whether the list is a \"Tautonym\". A Tautonym is defined as a word or term where the same word appears consecutively without any modification. Your task is to create a function that checks for Tautonyms in a given list of words and retur...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5697, "level": 1, "question": "Given a list of space-separated words, determine whether the list is a \"Tautonym\". A Tautonym is defined as a word or term where the same word appears consecutively without any modification. Your task is to create a function that checks for Tautonyms...
def isPermutationPalindrome(s): freq = {} for c in s: if c in freq: freq[c] += 1 else: freq[c] = 1 odd_count = 0 for count in freq.values(): if count % 2 != 0: odd_count += 1 if len(s) % 2 == 0: return odd_count == 0 else: ...
simplelr_Apps
[ { "content": "Question:\n## Palindrome Permutation\n\nA palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Given a string `s`, write a function that determines whether any permutation of `s` is a pal...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5698, "level": 1, "question": "## Palindrome Permutation\n\nA palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Given a string `s`, write a function that determines whet...
def print_hello_world(): for _ in range(5): print("Hello, World!") # Example usage: print_hello_world()
simplelr_Filter
[ { "content": "Question:\nIn this problem, we will work with the string \"Hello, World!\". Write a Python function that will print the string \"Hello, World!\" 5 times using a loop.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 5699, "level": 1, "question": "In this problem, we will work with the string \"Hello, World!\". Write a Python function that will print the string \"Hello, World!\" 5 times using a loop.", "split": "train" }