task_id
large_stringlengths
15
15
language
large_stringclasses
1 value
title
large_stringlengths
6
34
instruction
large_stringlengths
116
2.25k
completion
large_stringlengths
85
3.88k
test_file
large_stringlengths
28
2.53k
test_list
listlengths
1
14
signature
large_stringlengths
19
162
categories
listlengths
1
8
test_setup
large_stringlengths
24
1.21k
lbpp/python/100
python
merge_partially_sorted_linked_list
Consider two linked lists where each node holds a number and each list is partially sorted in ascending order from the head of the list to the tail so that each number is at most k positions away from its correctly sorted position. Write a python program that returns the merge of the two linked lists. The linked list c...
import heapq class ListNode: def __init__(self, value: int): self.value = value self.next = None def sort_list(list_head: ListNode, k: int) -> ListNode: result = None result_head = None heap = [] n = 0 while n < k: if not list_head: break heapq.h...
eJy1Us1ugkAQ7sEHmdiLJEgUq7Ym9lRvjZd6aCKEEBnqprCQZenPrQ/Rvm9ndwFptNY0cRMIO/Pt97PMR+er7Fzo9cjpoxuLLIVNFiGwNM+EhHtWyCXtbUhRPGGQh0KyMEneg4LaGAUJATzu8UtYLR5WHo8wBlULZEY9/oyR2vWYxLSY6c6acelb0L9tyGceB1pbDCOYN9XewDL1TSkEckkthTC1OBOgOIFxMNym3sI7HN9km0/hrD0YIdoHTF+gLAXXelW1TlYnMvkoGVcBGhGdq0lZmdIGSWftm/3rliUIfJe8ATlhniOPNKnzEiYl...
[ "def list_to_linkedlist(items: list[int]) -> ListNode:\n head = ListNode(0)\n current = head\n for item in items:\n current.next = ListNode(item)\n current = current.next\n return head.next\n\ndef linkedlist_to_list(node: ListNode) -> list[int]:\n items = []\n while node:\n it...
def merge_partially_sorted_list(firstlist_head: ListNode, secondlist_head: ListNode, k: int) -> ListNode:
[ "linked list" ]
from code import ListNode, merge_partially_sorted_list
lbpp/python/101
python
min_g_c_d_subsets
You are given an array of integers, each of which is greater than 1. This array needs to be split into subsets such that the greatest common divisor within each subset is greater than 1. Write a Python program to return the minimum number of subsets required to create such a split.
import math def min_g_c_d_subsets(nums: list[int]) -> int: best = len(nums) def search(i: int, gcds: list[int]) -> None: nonlocal best if i == len(nums): best = min(best, len(gcds)) return for j, g in enumerate(gcds): new_g = math.gcd(g, nums[i]) ...
eJxrYJnawcgABhGNQIZSWlF+rkJyfkqqQmZuQX5RiUJuZl58enxyfEp8cWlScWpJcUxeTJ6yQohrcEhMXmJxcSo2NRrRRjoKxjoKJrGaCra2CkYwHfGufi7E6DY01VEAImMKtBsZ6CiY6ShY6CgYAilDIzKNMgY7xBJoHpAyNAfyDIFsuM9MyHGaoQE4cLA5SWmKHgAG3Xkb
[ "assert min_g_c_d_subsets([2, 3, 4]) == 2", "assert min_g_c_d_subsets([15, 5, 3]) == 2", "assert min_g_c_d_subsets([15, 20, 6, 8, 16, 12]) == 2", "assert min_g_c_d_subsets([3, 5, 9, 25, 17, 51, 2, 4]) == 4", "assert min_g_c_d_subsets([15, 10, 3, 2]) == 2" ]
def search(i: int, gcds: list[int]) -> None:
[ "math", "recursion", "brute force" ]
from code import min_g_c_d_subsets
lbpp/python/102
python
min_square_in_base
You are given a number `number` where you can assume that all digits are between 0 and 9. You need to return the smallest numerical base (`base`) such that that `number` expressed in the numerical base `base` is a perfect square. The maximal number you will get is smaller than 1000000000 (in decimal base). Give a pytho...
def min_base_is_square(x: str) -> int: def convert_to_base_10(x: str, base: int): power = 0 val = 0 for digit in x[::-1]: val += int(digit) * (base**power) power += 1 return val def is_square(x: str, base: int, are_squares: set[int]): """ ...
eJxrYJmaxMgABhHRQIZSWlF+rkJyfkqqQmZuQX5RiUJuZl58UmJxanxmcXxxYWliUWpMXkyeskKIa3BITF5icXEqVkUaMUpmhjFKmgq2tgoWMPXxrn4uxOk1NDQwgOo2Jl23qYElVLOhERm6DWFWG5qR4XIDQ2OodhTdSlP0AE1fc+0=
[ "assert min_base_is_square(\"61\") == 8", "assert min_base_is_square(\"1100\") == 3", "assert min_base_is_square(\"509\") == 12", "assert min_base_is_square(\"510\") == 16", "assert min_base_is_square(\"1013\") == 6" ]
def is_square(x: str, base: int, are_squares: set[int]):
[ "math" ]
from code import min_base_is_square
lbpp/python/103
python
min_stops_around_stations
You are given two integer arrays of equal length: gas and cost. The value at gas[i] represents the amount of gas at gas station i and cost[i] represents the amount of gas required to reach the next gas station (i+1). The last value in the cost array represents the cost to go back to the first station from the last. You...
def min_stops_around_stations(gas: list[int], cost: list[int], current_idx: int = 0, gas_in_car: int = 0, no_stops_made: int = 0) -> int: if gas_in_car < 0: return -1 if current_idx == len(gas): return no_stops_made min_if_included = min_stops_around_stations(gas, cost, current_idx+1, gas_...
eJxrYJnqzcIABhEuQIZSWlF+rkJyfkqqQmZuQX5RiUJuZl58cUl+QXF8YlF+aV4KkJNYkpmfVxyTF5OnrBDiGhwSk5dYXJyKT61GtKGOgpGOgnGsjgKUaRKrqWBrq6BrCDMl3tXPhSITjSEmGlNgoCnQIAwnUmKgGcgUdAONyDXQHEcgUhKG5tgMJNuFUFOAZuooWCJFDThoDakT5SZghMt0U4oNN8VtuAllhlvQ0nBLvIaTnYiNiTAcJbkoTdEDACpvUBk=
[ "assert min_stops_around_stations([1, 2, 3], [1, 2, 4]) == -1", "assert min_stops_around_stations([1, 2, 3], [1, 2, 3]) == 3", "assert min_stops_around_stations([1, 5, 2], [1, 2, 4]) == 3", "assert min_stops_around_stations([1, 6, 4], [1, 2, 4]) == 2", "assert min_stops_around_stations([7, 2, 3], [1, 2, 4])...
def min_stops_around_stations(gas: list[int], cost: list[int], current_idx: int = 0, gas_in_car: int = 0, no_stops_made: int = 0) -> int:
[ "recursion", "backtracking" ]
from code import min_stops_around_stations
lbpp/python/104
python
min_swaps_palindrome
Given a string that is not palindromic, write a Python program to compute the number of swaps you need to make between positions of characters to make it a palindrome. Return -1 if no number of swaps will ever make it a palindrome. A swap is when you exchange the positions of two characters within a string. The string ...
def swap_indices(word: str, i: int, j: int) -> str: c1 = word[i] c2 = word[j] word = word[:j] + c1 + word[j + 1 :] word = word[:i] + c2 + word[i + 1 :] return word def is_palindrome(word: str) -> bool: return word == word[::-1] def is_palindrome_anagram(word: str) -> bool: odd_count = 0 ...
eJxrYJkaxswABhH+QIZSWlF+rkJyfkqqQmZuQX5RiUJuZl58cXliQXF8QWJOZl4KUD41Ji8mT1khxDU4JCYvsbg4FYcyjRil3MTcxBglTQVbWwVDmJ54Vz8XUvSnUGhACswFRuQaANWvS7YLqig2IYViXyQCzaDECKD2qqqqRIp8UliYm5ubmZ+fWUAdY3KhxhhTZAqlhmTm4jBEaYoeACGLI/I=
[ "assert min_swaps_palindrome(\"mama\") == 1", "assert min_swaps_palindrome(\"mamad\") == 1", "assert min_swaps_palindrome(\"mamda\") == 2", "assert min_swaps_palindrome(\"mamd\") == -1", "assert min_swaps_palindrome(\"mamdz\") == -1", "assert min_swaps_palindrome(\"mamddda\") == 2", "assert min_swaps_pa...
def min_swaps_palindrome(word: str) -> int:
[ "recursion", "backtracking" ]
from code import min_swaps_palindrome
lbpp/python/105
python
min_time_to_build_value
Let l be a a 2d array representing items that one could build after buying the necessary resources. Each item is represented by 3 integers: time to build, price in resources, and value. Write a Python program to find the group of items that minimize the time to build (you have to build the items one at a time), with t...
def min_time_to_build_value(l: list[list[int]], P: int, V: int) -> int: dp = [[[0 for _ in range(P + 1)] for _ in range(100 * len(l) + 1)] for _ in range(len(l) + 1)] for i in range(1, len(l) + 1): for j in range(0, 100 * len(l) + 1): for k in range(0, P + 1): dp[i][j][k] = ...
eJxrYJlayMIABhFZQIZSWlF+rkJyfkqqQmZuQX5RiUJuZl58SWZuanxJfnxSaWZOSnxZYk5pakxeTJ6yQohrcEhMXmJxcSpulRrR0SYGOgqGIGwaq6MQbY7CMwayTEECSBzTWCDHCMg2NtBUsLUFShrAbIt39XOhss1GA2WzJT6LDelqMZBhbAmx2ISeFoP0DJjFRiZgi83pba8p2FpjeltrRnNrDQ2x2WsIsdgMxWKlKXoAcJo47A==
[ "assert min_time_to_build_value([[40, 10, 15], [70, 10, 15], [30, 5, 10], [30, 5, 5]], 20, 30) == 100", "assert min_time_to_build_value([[40, 10, 15], [70, 10, 15], [30, 5, 12], [30, 5, 5]], 20, 30) == 100", "assert min_time_to_build_value([[40, 10, 15], [70, 10, 15], [30, 5, 9], [30, 5, 5]], 20, 30) == 110", ...
def min_time_to_build_value(l: list[list[int]], P: int, V: int) -> int:
[ "dynamic programming" ]
from code import min_time_to_build_value
lbpp/python/106
python
minimize_node_resources
You are given an integer N representing the number of nodes in a network. You are also given an 2d array of integers of size 2N. Each of those elements represent an edge where the first integer within that element represents the node that it is coming from and the second element represents the node that it is going to....
class Node: def __init__(self, value: int, importance: int): self.value = value self.outgoing = [] self.incoming = [] self.importance = importance self.resources = 1 def minimize_node_resources(N: int, edges: list[list[int]], importance: list[int]) -> int: nodes = [] ...
eJxrYJnKwsIABhF/mRkYlNKK8nMVkvNTUhUycwvyi0oUcjPzMnMzq1Lj84CC8UWpxfmlRcmpxTF5MXnKCiGuwSExeYnFxam4VWqY6ihERxvoKBjGAhmGOgpGINpIR8EYRBvrKJjEwiSAYkCujoJprKaCra2CoSnMjnhXPxeS7QPbA7OXKPuMqGqfCSH7LKlnHVKwErTW0JAse83w2WsIMp2g/ToKZlAnmNDRCSj2gzRREtmUO8EE7gTy4p9mLlCaogcAWZQfgA==
[ "assert minimize_node_resources(5, [[0, 1], [1, 2], [2, 3], [3, 4]], [1, 2, 3, 4, 5]) == 15", "assert minimize_node_resources(5, [[0, 2], [0, 1], [2, 3], [3, 4]], [1, 2, 3, 4, 5]) == 12", "assert minimize_node_resources(5, [[0, 2], [0, 1], [2, 4], [3, 4]], [1, 2, 3, 4, 5]) == 9", "assert minimize_node_resourc...
def minimize_node_resources(N: int, edges: list[list[int]], importance: list[int]) -> int:
[ "graph" ]
from code import minimize_node_resources
lbpp/python/107
python
minimize_pack_vectors
You are given a list L containing n integer vectors with numbers in [1, v], where v>1. Each vector can have a different size, denoted as s_i. You are also given a number c, which we call a context window. Assume that s_i <= c. The goal is to create a new list of integer vectors P with a uniform size of c, using the ...
def minimizePackVectors(L: list[list[int]], c: int) -> list[list[int]]: bestP = [] def search(i: int, P: list[list[int]]): nonlocal bestP if i == len(L): if len(bestP) == 0 or len(P) < len(bestP): bestP = [l.copy() for l in P] return for j in rang...
eJytVMFOwkAQ9UC8+BMTvEDcmF0stD1wkxsxJBJjwjaEwGI22i0pxBhPfoT+r7OzxVbAtgGbdtpuZt9786bTj8bXxfkZHY8NfGgu0ySGebJQoONVkm4g1kbH+l2NZvPnBzXfJOlaGmkuYTy4H0szhD5MJoJBh8FNxGDiMegy6NlH34YgiqQZYdYBoNYQM9vSqLcVLqjFqAjGgDPwMRZQaS2wawg6W68VCsRNffhB2CqbDu5uD6m0YAjt2Xu3Qlr3D2mc1DkIesvOo0U5PCSsEOTtCjqBkFzNSsi6VU7ulzbKc+3aAhZtOdYZDcskBQ3a...
[ "L = [[1, 2, 3], [4, 5, 6], [7], [8]]\nP = minimizePackVectors(L, 6)\nexpectedP = [[1, 2, 3, 0, 7, 0], [4, 5, 6, 0, 8, 0]]\nassert P == expectedP", "L = [[1, 2], [3, 4], [5]]\nP = minimizePackVectors(L, 5)\nexpectedP = [[1, 2, 0, 3, 4], [5, 0, 0, 0, 0]]\nassert P == expectedP", "L = [[1, 2, 3, 4, 5]]\nP = minim...
def search(i: int, P: list[list[int]]):
[ "list", "backtracking", "recursion" ]
from code import minimizePackVectors
lbpp/python/108
python
minimum_possible_number
Given the number of students that attended school for each day, and k number of days, the principal wants to find the minimum possible number n such that there are at least k days where the attendance is <= n. Write a program to help the principal. You should solve this using constant extra space and without modifying ...
import math def minimumPossibleNumber(attendance: list, k: int) -> int: start = min(attendance) end = max(attendance) n = math.inf while start <= end: mid = (start + end) // 2 days = 0 for i in attendance: if i <= mid: days += 1 if days >=...
eJxrYJk6jZEBDCL6gQyltKL8XIXk/JRUhczcgvyiEoXczLzM3NLcgPzi4syknFS/0tyk1KKYvJg8ZYUQ1+CQmLzE4uJUXOo0oo0MDHQUDEGECYgwBhFAsVggU1PB1hbEhhkV7+rnQqyxhiCzdBRMdRTMwQwzoPk6ChYwEUuwiClYBMI1BtpoArbRhDz7wG42BJsA4pBjiLkp0NUWoBAwA7EsoUEDMtgUq8FKU/QAjFt4GA==
[ "assert minimumPossibleNumber([200, 100, 400, 300, 200], 3) == 200", "assert minimumPossibleNumber([10, 3, 5, 7, 3, 6, 4, 8, 5, 7, 9, 6, 5, 8, 7, 9, 3], 4) == 4", "assert minimumPossibleNumber([1000], 1) == 1000", "assert minimumPossibleNumber([750, 800, 650, 900, 1000], 5) == 1000" ]
def minimumPossibleNumber(attendance: list, k: int) -> int:
[ "sorting" ]
from code import minimumPossibleNumber
lbpp/python/109
python
monte_carlo_cards
Write a monte carlo function in Python to compute the median number of cards you'd need to draw from a deck such that the sum equals or exceeds the value V. The deck is a classic 52 card deck, each face card is worth 10 points and the other cards are worth the number on the card.
from random import random def monte_carlo_cards(V: int) -> float: n = 10000 deck = [i % 13 + 1 for i in range(52)] deck = [min(deck[i], 10) for i in range(52)] results = [0.0] * n for i in range(n): sum = 0 count = 0 while sum < V: sum += deck[int((random() * 52)...
eJxrYJn6hwECen4opRXl5yok56ekKmTmFuQXlSjk5ueVpMYnJxbl5IPIlOKYvJg8ZYUQ1+CQmLzE4uJUoJrEpGINDHUaRgYGmgq6CsaGekDaxlYBSMN0xrv6uRBpijHEFBMzikwxg5hiaYTdFKUpegAlzlJJ
[ "assert abs(monte_carlo_cards(200) - 31.0) <= 1.0", "assert abs(monte_carlo_cards(300) - 46.0) <= 1.0", "assert abs(monte_carlo_cards(600) - 92.0) <= 1.0" ]
def monte_carlo_cards(V: int) -> float:
[ "simulation", "monte carlo" ]
from code import monte_carlo_cards
lbpp/python/110
python
nb_digits_base_k
Write a python function `nb_digits_base_k(n: int, k: int) -> int` that returns the number of digits in the base-k representation of n.
def nb_digits_base_k(n: int, k: int) -> int: if n == 0: return 1 count = 0 while n > 0: count += 1 n //= k return count
eJxrYJl6hQECei4opRXl5yok56ekKmTmFuQXlSjkJcWnZKZnlhTHJyUWp8Znx+TF5CkrhLgGh8TkJRYXp2JRomFooKNgpKlga6tgAlMc7+rnQlijhZmOgjFYoylpGoEWGkJsNETWqDRFDwAeGEeK
[ "assert nb_digits_base_k(10, 2) == 4", "assert nb_digits_base_k(86, 3) == 5", "assert nb_digits_base_k(0, 12) == 1" ]
def nb_digits_base_k(n: int, k: int) -> int:
[ "math" ]
from code import nb_digits_base_k
lbpp/python/111
python
negation_decorator
Write a generic python decorator `negation_decorator(func)` that wraps any function that returns a number, and returns a new function that takes the same arguments and returns the number multiplied by -1.
def negation_decorator(func): def wrapper(*args, **kwags): return -1 * func(*args, **kwags) return wrapper
eJxrYJlayMgABhFZQIZSWlF+rkJyfkqqQmZuQX5RiUJeanpiSWZ+XnxKanJ+UWJJflFMXkyeskKIa3BITF5icXEqVkUaOYm5SSmJVgqGmhqaCra2CrqGMF3xrn4uxJugADQjUVPDCGKIEbmG6CgkAc1R0FZI0tQw1DPQUTDSM4AYaaxnQKahWolF6cU6Clpa2eUglpUChI6OUSpLzIlRitXUANK2plkQe0yzkK1RmqIHAMr+eWc=
[ "assert negation_decorator(lambda: 1)() == -1", "assert negation_decorator(lambda a: a)(2) == -2", "assert negation_decorator(lambda a, b: a + b)(1.0, 2.0) == -3.0", "assert negation_decorator(lambda *args, **kwargs: kwargs[\"val\"])(val=5j) == -5j" ]
def wrapper(*args, **kwags):
[ "decorators", "math" ]
from code import negation_decorator
lbpp/python/112
python
new_most_affected_locations
You are supervising a conservation project focusing on the population of 4 endagered bird species in a nature reserve. You are provided with 3 nd numpy arrays The first array `initialPopulation` is a 4x2x4 array which contains intial population of birds in the reserve where element (i,j,k) represents the population of ...
import numpy as np def new_most_affected_locations( initialPopulation: np.ndarray, location: np.ndarray, currentPopulation: np.ndarray ) -> np.ndarray: result = np.copy(location) for i in range(4): for j in range(2): populationDecrease = initialPopulation[i, j] - currentPopulation[i, ...
eJzdVslOwzAQ5cCNn7Dg0koWspu6DQducEUIOCA1VRQVV4qUOiGLgBsfAf/LeGLTNiZdKEWISE6tzmbPe6/T18P37OgAn/sYNsfTPJ2RSfogSTzL0rwkSj6Fs7Qow2g6lZNSPoRJOonKOFVFoKxPNcteSFQQlQUqUCfk7vL2DqwqLuMouU6zKsEIcg4ep1GeRy+dQBF4RvUHbkc9RklPUOLB6osxJSMBuwGsISxfjMd0yV27QkgflmDafQC7ISwf1hlruGvXOjO4Y/Z5ZnBvZkdXzAxHwOzzzJRwNk8/DlRXX9v2Zc0tdbROxylpHpEb...
[ "initialPopulation = np.array(\n [\n [[20, 25, 35, 45], [55, 65, 75, 85]],\n [[25, 30, 40, 50], [60, 70, 80, 90]],\n [[30, 35, 45, 55], [65, 75, 85, 95]],\n [[35, 40, 50, 60], [70, 80, 90, 100]],\n ]\n)\n\nlocation = np.array(\n [\n [[0, 1], [1, 0]],\n [[1, 1], [0,...
def new_most_affected_locations( initialPopulation: np.ndarray, location: np.ndarray, currentPopulation: np.ndarray ) -> np.ndarray:
[ "numpy" ]
from code import new_most_affected_locations import numpy as np
lbpp/python/113
python
number_of_viable_islands
I’m trying to host a party on an island. I have a map represented as a grid which is m x n. The '1's in the grid represent land, and '0's represent water. There are many islands I want to go to, but I’m not sure how many are big enough for my party. I want to know the number of islands that could hold the people at my ...
def expand(grid: list[list[int]], i: int, j: int, visited: dict[int, set[int]], current_island: dict[int, set[int]]) -> None: if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0 or (i in visited and j in visited[i]): return if i not in visited: visited[i] = set() visi...
eJxrYJmazMYABhExQIZSWlF+rkJyfkqqQmZuQX5RiUJeaW5SalF8flp8WWZiUk5qfGZxTmJeSnFMXkyeskKIa3BITF5icXEqHqUa0dGGOgpAZABBsToKmAIGMB5IBlMAKGKoqWBrq2AEszbe1c+Fjk4wGHgngEPB1ADsBgNau8GQsBsMqekGA7gY1EpDGEINGANoVJgMAjfQIi4M0OOCgBuMDaiUJmGxjREOhuhuQHYlddMDBW6wHARusBgEbjA0oFaipMgRYDcYI7tBaYoeABWurUQ=
[ "assert number_of_viable_islands([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1]], 1) == 2", "assert number_of_viable_islands([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 0]], 1) == 2", "assert number_of_viable_islands([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 1], [...
def number_of_viable_islands(grid: list[list[int]], X: int) -> int:
[ "graph", "traversal" ]
from code import number_of_viable_islands
lbpp/python/114
python
obstacle_grid
You are given an mxn matrix where 1 represents an obstacle and 0 represents an empty cell. You are given the maximum number of obstacles that you can plow through on your way from the top left cell to the bottom right cell. Write a Python program to return the number of unique paths from the top left cell to the bottom...
def obstacle_grid(grid: list[list[int]], k: int) -> int: min_moves = [[0 for _ in range(k+1)] for _ in range(len(grid)*len(grid[0]))] for s in range(k+1): min_moves[0][s] = 1 for s in range(k+1): for i in range(len(grid)): for j in range(len(grid[0])): index = i*l...
eJxrYJl6g5kBDCIuAhlKaUX5uQrJ+SmpCpm5BflFJQr5ScUlick5qfHpRZkpMXkxecoKIa7BITF5icXFqejyGtHRBjoKIBSrowBiGiKYYFEg20BTwdZWwQhmULyrnwsxhhrCjEGYYUiqGWCnGGI1y4AqZhmS5zesZhmBzTImOZzQAp98H2IxiUz/YTGJTN8hBxbVnIffUIhLTalrqDHYUDPqGmqCaajSFD0A2AAaHg==
[ "assert obstacle_grid([[0, 0, 0], [0, 1, 0], [0, 0, 0]], 0) == 2", "assert obstacle_grid([[0, 1], [0, 0]], 0) == 1", "assert obstacle_grid([[0, 0], [1, 1], [0, 0]], 0) == 0", "assert obstacle_grid([[0, 0], [1, 1], [0, 0]], 1) == 2", "assert obstacle_grid([[0, 0], [1, 1], [0, 0]], 2) == 3", "assert obstacl...
def obstacle_grid(grid: list[list[int]], k: int) -> int:
[ "math" ]
from code import obstacle_grid
lbpp/python/115
python
overlapping_intervals
You are given an array of unsorted intervals each of which is defined by two integers: a start time and end time. Write a Python program that outputs a list of tuples where each element contains 3 integers that represent an interval of time. The 3 integers represent the following: 1) The start time of the interval 2) T...
import heapq def overlapping_intervals(intervals: list[list[int]]) -> list[tuple[int, int, int]]: if len(intervals) == 0: return [] intervals_by_start = [(start, [start, end]) for start, end in intervals] intervals_by_start.sort(key=lambda x: x[0]) heapq.heapify(intervals_by_start) interva...
eJzNj8sKglAQhoN6kME2CofIS14W7mrbJheBikhZCHoUjdY9RL1Fu16wmTxCEkEQgm6+33HO8fsvk9tjPHo92zsG6VAVOeyKfQJpXhbVCYpzUmVxWab8GKX8lFTnOKsDHvApeKuNF/C4rpNve7Lvqwz0kIGvMTCICwYW0WRgh6ECrgu+jEv4XVUYyEgd3ygiDTFF4sE5RaQppkhL7CJtmoatWLRaL3+W7EghO9IDkrSFpDVkSVUjK7pjLnSdHnRtsYt08CRFh34pxhRU7b8eRttDEz2aQv0VIWn93b6pQhcbH1Wk6+wJ4DXm5A==
[ "assert overlapping_intervals([[1, 3], [2, 4], [5, 7], [6, 8]]) == [(1, 2, 1), (2, 3, 2), (3, 4, 1), (4, 5, 0), (5, 6, 1), (6, 7, 2), (7, 8, 1)]", "assert overlapping_intervals([[5, 7], [6, 8], [1, 3], [2, 4]]) == [(1, 2, 1), (2, 3, 2), (3, 4, 1), (4, 5, 0), (5, 6, 1), (6, 7, 2), (7, 8, 1)]", "assert overlappin...
def overlapping_intervals(intervals: list[list[int]]) -> list[tuple[int, int, int]]:
[ "heap", "hashing" ]
from code import overlapping_intervals
lbpp/python/116
python
overlapping_rectangles
Given a list of rectangles placed on top of each other, each of which is represented by 3 integers (leftmost x, rightmost x, height), write a Python program to determine the visible surface area of each rectangle. All of the rectangles have their bottom edge on the same level. Some of the surface area of a rectangle ma...
def is_square_in_rectangle(rect: tuple[int, int, int], x: int, y: int) -> bool: """Check if a square with coordinates left=x, right=x+1, bottom=y, top=y+1 is in the rectangle""" return rect[0] <= x < rect[1] and 0 <= y < rect[2] def overlapping_rectangles(rects: list[tuple[int, int, int]]) -> list[int]: v...
eJxrYJm6gZEBDCJWAhlKaUX5uQrJ+SmpCpm5BflFJQr5ZalFOYkFBZl56fFFqckliXnpOanFMXkxecoKIa7BITF5icXFqTgVakRrGOgoGAKRpo4CiGkEYsZqKtjaKkSDhGNhBsW7+rmQZKgRwlBDJEOBwgbkGwpzqSHYfCOEo42QHG1EkbvxWAERNdFRMEazTUfBHMVCpSl6AAdrfo8=
[ "assert overlapping_rectangles([(0, 1, 1), (0, 2, 1)]) == [1, 1]", "assert overlapping_rectangles([(0, 2, 1), (0, 1, 1)]) == [2, 0]", "assert overlapping_rectangles([(0, 1, 1), (1, 2, 2), (0, 2, 2)]) == [1, 2, 1]", "assert overlapping_rectangles([(0, 1, 1), (1, 2, 2), (0, 2, 2), (1, 4, 3)]) == [1, 2, 1, 7]" ]
def overlapping_rectangles(rects: list[tuple[int, int, int]]) -> list[int]:
[ "math" ]
from code import overlapping_rectangles
lbpp/python/117
python
pack_vectors
You are given a list L containing n integer vectors with numbers in [1, v], where v>1. Each vector can have a different size, denoted as s_i. You are also given a number c, which we call a context window. Assume that s_i <= c. The goal is to create a new list of integer vectors P, where each vector has a uniform size o...
def packVectors(L: list[list[int]], c: int) -> list[list[int]]: P = [] currP = [] r = 0 for i in range(len(L)): s_i = len(L[i]) if s_i > c: return [] if s_i < r: currP = currP + [0] + L[i] else: P.append(currP + [0] * r) ...
eJztVU1rwkAQ7aG3/onBXhSW4mw+jAdv9SZFqJSCCSIaS2jdSJTSY39E+3+7uzHJJCYahbYILhpfZndn3ryZwc/r78HNlV7PfQkaiyhcwiyc+xAsV2G0gdV09vrkzzZhtHaFK25h1H8cuWIAPRiPkQFnYDAwPQZjS0NU0PQ8VwzlGXK9OWDQabnC/1hJgz8fFlwwaMcf4ksbtjvK5XS99iUpebUHqZ+E1aT/cF/NkIGlHNuSBAOHQVe616G43rS1ESt4W3t513V8LHtXgFw5lbcmS/vtpO9JWHkytcU/apkswzbBzharK+V5O4fqlRLJ...
[ "L = [[1, 2, 3, 4], [5, 3, 1], [4]]\nP = packVectors(L, 7)\nexpectedP = [[1, 2, 3, 4, 0, 0, 0], [5, 3, 1, 0, 4, 0, 0]]\nassert P == expectedP", "L = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [2, 4, 6, 8, 1]]\nP = packVectors(L, 5)\nexpectedP = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [2, 4, 6, 8, 1]]\nassert P == expectedP"...
def packVectors(L: list[list[int]], c: int) -> list[list[int]]:
[ "list", "greedy" ]
from code import packVectors
lbpp/python/118
python
pairwise_map
Declare two TypeVar T and U. In the same code block, write a python function, generic over types T and U pairwise_map(values: List[T], operation: Callable[[T, T], U]) -> List[U] that calls `operation` with all pairs of in the list `values` and return a list i.e. [operation(values[0], values[1]), operation(values[1], va...
from typing import Callable, TypeVar T = TypeVar("T") U = TypeVar("U") def pairwise_map(values: list[T], operation: Callable[[T, T], U]) -> list[U]: output_list = [] for first_index in range(len(values) - 1): first_arg = values[first_index] second_arg = values[first_index + 1] output_...
eJxrYJkqzMQABhE8QIZSWlF+rkJyfkqqQmZuQX5RiUJBYmZReWZxanxuYkFMXkyeskKIa3BITF5icXEqmrRGdKyOQk5iblJKokKijkKSlUKigrZCkqaCra1CdCxMa7yrnwsBYwypZY6OgpGOgrGOggm6gRogShNiogZImaaOggZILYgGadCkjj1++XmpEFtALB0FBEmi+YYQ83UUTIEIM3iANkDDJyZPAQhCikpTdSBMt8ScYkJsqHIUNylN0QMAxPCeqg==
[ "assert pairwise_map([], lambda a, b: a + b) == []", "assert pairwise_map([1], lambda a, b: a + b) == []", "assert pairwise_map([1, 2, 3, 4], lambda a, b: (a, b)) == [(1, 2), (2, 3), (3, 4)]", "assert pairwise_map([1, 2, 3, 4], lambda a, b: None) == [None, None, None]", "assert pairwise_map([1, 1, 3, 4, 5, ...
def pairwise_map(values: list[T], operation: Callable[[T, T], U]) -> list[U]:
[ "list" ]
from code import pairwise_map
lbpp/python/119
python
pd_row_sum_with_next
Write a python function `pd_row_sum_with_next(df: pd.DataFrame) -> pd.DataFrame` that takes a pandas DataFrame `df` and returns a new DataFrame with the same columns as `df` and one additional column `sum` such that df.iloc[i].sum contains df.value.iloc[i] + df.value.iloc[i+1] if i > len(df) and df.iloc[i].diff contain...
import pandas as pd def pd_row_sum_with_next(df: pd.DataFrame) -> pd.DataFrame: df["sum"] = df["value"] + df["value"].shift(-1, fill_value=0) return df
eJzFkE1LwzAYxz3sA3jz+hAvLZTSV8RAb5tHL+4gmFFi07GCTUqbOaEU/BD6fU0bs63DgYyJIfAkeV7y+//fJ59Xk4thPV6qA1rWooRMsByKshK1hIqltdikzbpMN4VcpTx/k4SbJOWMNqB2xQgn/Brms4c54WwJiXpyp1TSu5qWudUS9Epf1jlBGJ58BwIHQgciB+KFAwQJucrrIUcQJah/etYh04HpoPoXnU04bZr8CJzFlrYrRcqKTFo2JAm0hINaewSth0FB+LjnCHCPEuKeJsIQd46p31L19d9gPjZsATZ4ITaEEdaQuxmKzUwI...
[ "df = pd.DataFrame({\"value\": [1, 2, 3, 4, 5], \"other\": [\"a\", \"b\", \"c\", \"d\", \"e\"]})\nassert pd_row_sum_with_next(df).to_dict() == {\n \"value\": {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},\n \"other\": {0: \"a\", 1: \"b\", 2: \"c\", 3: \"d\", 4: \"e\"},\n \"sum\": {0: 3, 1: 5, 2: 7, 3: 9, 4: 5},\n}", "d...
def pd_row_sum_with_next(df: pd.DataFrame) -> pd.DataFrame:
[ "pandas" ]
from code import pd_row_sum_with_next import pandas as pd
lbpp/python/120
python
pd_total_expense_of_each_month
Write a python function `pd_total_expense_of_each_month(df: pd.DataFrame) -> Dict` that takes a pandas DataFrame `df` and returns a new dict where each month is the key (in format YYYY-MM) and the value is a subdict which contains: - the key "total" with value the total expenses of each month - the key "all" with value...
import pandas as pd from typing import Any from collections import defaultdict def pd_total_expense_of_each_month(df: pd.DataFrame) -> dict[str, Any]: month_to_rows = defaultdict(list) for _, row in df.iterrows(): month = row["date"].strftime("%Y-%m") month_to_rows[month].append(row.to_dict())...
eJztk0FLwzAUxz148Bt4k1AvG7SjybSwwW6bRy/uICylhCVlhTUtbQ7CGPgh9Pv6kq6u7dRlMA+CIZCQ/N97/5f++nr5fnN1YcbzNWycuMhStMy4QEmaZ4VCOY9Uptg6Ei+5kKWIsjgSbLmK0kyqFZW1jEnOSgQz51RSeYvms6c5lTxGEzgaTJliDwVLRY9KBGNTLXpQhzMlqDNGi/2hHhA2T1JRKpbmPeoQH488H8OkTt89IiX+idKh35aGbtPhrnlj8s5FxEW4Fmyp7EOfps2fnqrHY9Dpq6USWr57gs/GdPINdUwKvYc61GHrdVU0...
[ "df = pd.DataFrame(\n {\n \"date\": [\n pd.Timestamp(\"2019-01-01\"),\n pd.Timestamp(\"2020-01-01\"),\n pd.Timestamp(\"2020-01-30\"),\n ],\n \"expense\": [4, 2, 1],\n }\n)\nd = pd_total_expense_of_each_month(df)\nexpected = {\n \"2019-01\": {\"total\": ...
def pd_total_expense_of_each_month(df: pd.DataFrame) -> dict[str, Any]:
[ "pandas", "date" ]
from code import pd_total_expense_of_each_month import pandas as pd
lbpp/python/121
python
penalty_path
You are given a weighted directed graph where each node has a penalty associated with it that is applied to every route that passes through that node. You are also given the start node and the target node. The inputs to this function are a dict representing the mapping between the id of the node and the penalty associa...
class Node: def __init__(self, id: int, penalty: int): self.id = id self.penalty = penalty self.outgoing_edges = [] self.incoming_edges = [] self.distance = float("inf") def __lt__(self, other) -> bool: return self.distance < other.distance def __eq__(self, ...
eJzVlM1KxDAUhV2Iz3EYNx0IktykIIXunK0bZyEYGYoTRxnntky7ERF8CH0Edz6kaexQFf+mUgezOYf8fjm55G774WlnK7TjR28G58t8gbN86nC5KPJlhcJxdlVdT4qsurBseRfj0dHYMiPFjUygBFQCEqAE+taym85c6cdOIinC4FAg8kqNlY09tVxWmT8ghbTs3czVnizPvcSWs7J0786PWCDsLxDWCrysE5gPkaZQK7zJ6PDgr1BNf6j7a6LG36Aq1Yk13ggrdWKljbDq/libchXQCYyASRB/zU0tt65trc0Er6a+jbdeZXtH3e6w...
[ "n = {0: 1, 1: 2, 2: 3}\nedges = [(0, 1, 1), (1, 2, 1), (0, 2, 1)]\nstart = 0\ntarget = 2\nk = 5\nassert penalty_path(n, edges, start, target, k) == 1", "n = {0: 1, 1: 2, 2: 3}\nedges = [(0, 1, 1), (1, 2, 1), (0, 2, 1)]\nstart = 0\ntarget = 2\nk = 4\nassert penalty_path(n, edges, start, target, k) == 1", "n = {...
def penalty_path(n: dict[int, int], edges: list[tuple[int, int, int]], start: int, target: int, k: int) -> int:
[ "graph" ]
from code import penalty_path
lbpp/python/122
python
pendulum_nums
Write a python function "def pendulum_nums(input: list[int]) -> list[int]" that takes a list of integers and reorder it so that it alternates between its most extreme remaining values starting at the max then the min, then the second greatest, then the second least, etc. until the median is approached.
def pendulum_nums(input: list[int]) -> list[int]: ascOrder = sorted(input) descOrder = sorted(input, reverse=True) output = [] for i in range(len(input)): if i % 2 == 1: output.append(ascOrder.pop(0)) else: output.append(descOrder.pop(0)) return output
eJx90E8LgjAYBvCIPkG3bi92KZjh5rQ8dMtrlzoEKRG5IGizpt77EPV9258SDJp48B2Pv+dlj8Fr1O+ZZzdUH95ZlhxOZcHgwm+lrOHGRNFcG34QDa8ykYkxiFIwkOzeXCQr9ME23WwzUbOqDmAJe4yAIAgR0DwTx6piv8zERKewVGGKAJswyb/UIV2vuizWbIDg87pYbNlO+B9LNOtjlUoSE54v1B5ql0US0VgPcUTV6JOQRvHcRNSIXf3E9rdC+++H+mkLbKG+AseioblWV21oa7EDoRpxGdQaHcJ7zt4Vop+T
[ "test0 = [1, 2, 3, 4]\nassert pendulum_nums(test0) == [4, 1, 3, 2]", "test1 = [0, 0, 0, 0]\nassert pendulum_nums(test1) == [0, 0, 0, 0]", "test2 = [-10, 99, 0, 78, 23, 8954678, 6543, -234567, 0, 3, 1]\nassert pendulum_nums(test2) == [8954678, -234567, 6543, -10, 99, 0, 78, 0, 23, 1, 3]", "test3 = [1]\nassert ...
def pendulum_nums(input: list[int]) -> list[int]:
[ "list", "loop" ]
from code import pendulum_nums # none required
lbpp/python/123
python
perfect_square_cube
Write a function "def perfect_square_cube(input: int) -> bool" that takes a float as input and determine whether it is both a perfect square and a perfect cube. Write it in Python.
import math def perfect_square_cube(input: float) -> bool: if input >= 0: if (input**0.5 % 1 == 0) and ( (math.isclose(input ** (1 / 3) % 1, 0, abs_tol=1e-9)) or (math.isclose(input ** (1 / 3) % 1, 1, abs_tol=1e-9)) ): return True return False
eJxrYJlqzMQABhE6QIZSWlF+rkJyfkqqQmZuQX5RiUJBalFaanJJfHFhaWJRanxyaVJqTF5MnrJCXr5CYkpKZklmfl5iDlR1sUJRamFpZlFqCkhFiGtwSExeYnFxKnZzNHQNNRVsbRXcEnOKU2Ea4l39XIjSbADWG1JUSrpWQ/K1mpmQr9fEwNKMfN2mFISVJQV6LXBEktIUPQDSm8EH
[ "assert perfect_square_cube(-1) == False", "assert perfect_square_cube(0) == True", "assert perfect_square_cube(1) == True", "assert perfect_square_cube(64) == True", "assert perfect_square_cube(4096) == True", "assert perfect_square_cube(5) == False", "assert perfect_square_cube(9) == False", "assert...
def perfect_square_cube(input: float) -> bool:
[ "math" ]
from code import perfect_square_cube # no additional imports required
lbpp/python/124
python
permute_arrays
Write a python function "def permute_arrays(k: int, A: List[int], B: List[int]) -> str" that takes two n-elements arrays, [A] and [B], perform a permutation (re-arrangement of their elements) into some [A]' and [B]' such that the multiplication of [A]'[i] and B'[i] will be always equal or greater than k for all i where...
def permute_arrays(k: int, A: list[int], B: list[int]) -> str: if len(A) != len(B): raise Exception("[A] and [B] must have the same size.") A.sort() B.sort(reverse=True) count = 0 for i in range(len(A)): if A[i] * B[i] >= k: count += 1 if count == len(A): retu...
eJydkE0KwjAQhRU8yBA3Con4rwjdWZd1oQvFiJR2hIJNSlJBdx5Cb+fOizgtLQgu/JnNDO8x37zkUrs9qpW8Vnca2N7oGAIdIkRxok0KCZr4mOLON8Y/W6mkqoPShWtBIYYYZuLSXSyl8q3Ft61Gj8NmxGHIYcyhz6G7JWFAPdfI7Wyb4Dgg2dpdSFbidq43/YTutL9me/Pf0GKQsQXBBZEE4QXxxV/hU3OeSAVU33/N6wGp8BRgkoKbt0irEkfZyTxYLITiLTOfpNcs7Np6AsFDjmg=
[ "assert permute_arrays(3, [7, 6, 8, 4, 2], [5, 2, 6, 3, 1]) == \"YES\"", "assert permute_arrays(10, [7, 6, 8, 4, 2], [5, 2, 6, 3, 1]) == \"NO\"", "assert permute_arrays(-50, [-7, -6, -8, -4, -2], [5, 2, 6, 3, 1]) == \"YES\"", "try:\n permute_arrays(3, [7, 6, 8, 4, 2], [5, 2, 2, 6, 3, 1])\nexcept Exception:...
def permute_arrays(k: int, A: list[int], B: list[int]) -> str:
[ "list", "exception handling" ]
from code import permute_arrays # no imports needed
lbpp/python/125
python
phone_number_letters
Write a Python function `most_similar_digits(number: str, words: list[str]) -> set[str]` which takes as input a phone number, specified as a string of digits, and a list of unique words with the same length as the phone number. Each digit in the phone number can be mapped to a range of characters: 2->ABC, 3->DEF, 4->GH...
LETTER_TO_N = {"a": 2, "b": 2, "c": 2, "d": 3, "e": 3, "f": 3, "g": 4, "h": 4, "i": 4, "j": 5, "k": 5, "l": 5, "m": 6} LETTER_TO_N |= {"n": 6, "o": 6, "p": 7, "q": 7, "r": 7, "s": 7, "t": 8, "u": 8, "v": 8, "w": 9, "x": 9, "y": 9, "z": 9} def most_similar_digits(number: str, words: list[str]) -> set[str]: min_dif...
eJxrYJlaxsQABhH5QIZSWlF+rkJyfkqqQmZuQX5RiUJufnFJfHFmbmZOYlF8SmZ6ZklxTF5MnrJCiGtwSExeYnFxKnZVGjFKZhZmRjFKOgrR6n6hvq7qOgrqvv4hjiDaPyQATLt7+Qaox2oq2NoqVEMVQeRqYVbEu/q5UM06oLgTsnVOZNljbmlkArHH0cnVBWSui6u7N4iOcIyMAtFRTpHhcHvwKqLMfhSjgDSKVTD78Sqitv3O7hCjnTyQ/I8kiGKf0hQ9AH8QuLc=
[ "assert most_similar_digits(\"6862\", ['NUME', 'MOTA', 'OTPA', 'GJMP']) == {'NUME','OTPA'}", "assert most_similar_digits(\"6862\", ['NUME', 'MOTA', 'OTPA', 'NUMB']) == {'NUMB'}", "assert most_similar_digits(\"7924\", ['ABED', 'DEGK', 'XAYZ', 'ZBYW']) == {'ABED', 'DEGK', 'XAYZ', 'ZBYW'}", "assert most_similar_...
def most_similar_digits(number: str, words: list[str]) -> set[str]:
[ "set", "list" ]
from code import most_similar_digits
lbpp/python/126
python
portfolio_analysis
Write a Python function `portfolio_analysis(positions: List[Position]) -> Tuple[Dict[str, float], Dict[str, float]` that takes a list of dictionaries representing positions in an investment portfolio, with a "risk" mapping to a string, a "country" mapping to a string, and a "dollar_value" mapping to a float and produce...
from typing import TypedDict from collections import defaultdict class Position(TypedDict): dollar_value: float risk: str country: str def portfolio_analysis(positions: list[Position]) -> tuple[dict[str, float], dict[str, float]]: risk_allocations = defaultdict(lambda: 0.0) country_allocations =...
eJzNUdFKwzAU9WEfcokvG4Sh63AgVBDdqy+bIDSlhK3bglmuJJsySsGP0P+1SdpNsZ0bezEPSbgn99yTc95bnzetM7eeBsWFzDQuYYLTFMTyBfUK7DZDKTDhisuNEYYpps5hPByNmeLGpLWP2lHcgTCEdpZTyPJO1ZIMH+4Pas8Y0cI8M3INjCzEfMEILW4TXKuV3vjy3a0vTlFKrpNXLtepRS67F3k5nikoVlZReIxuq5ZhW2sQaWUYCjqdC1QGwjq5njDyR8l9knzaQCXx7Qim3o4pdv8rDXdfiiphsXWqGPoLdsMc2vuOeiMiP9bB...
[ "assert portfolio_analysis([]) == ({}, {})", "assert portfolio_analysis([{\"risk\": \"high\", \"country\": \"CA\", \"dollar_value\": 1.0}]) == (\n {\"high\": 1.0},\n {\"CA\": 1.0},\n)", "risks, regions = portfolio_analysis(\n [\n {\"risk\": \"high\", \"country\": \"CA\", \"dollar_value\": 1.0},\...
def portfolio_analysis(positions: list[Position]) -> tuple[dict[str, float], dict[str, float]]:
[ "list", "dictionary" ]
from code import portfolio_analysis
lbpp/python/127
python
possible_remainders
Given an integer n, generate all the possible remainders of perfect squares of integers when divided by n. Return a list containing the possible remainders in ascending order. Write it in Python.
def possibleRemainders(n: int) -> list[int]: remainders = set() for i in range(n): # Iterating up to n is enough to find all possible remainders remainders.add((i**2) % n) return sorted(list(remainders))
eJxrYJlqwMgABhGaQIZSWlF+rkJyfkqqQmZuQX5RiUJBfnFxZlJOalBqbmJmXkpqUXFMXkyeskKIa3BITF5icXEqVkUaRpoKtrYK0QY6CoaxQPUwLfGufi7EaDdHaNdRMNJRMCHHEFNkQ8gywRjVF3C9SlP0ABg8YwQ=
[ "assert possibleRemainders(2) == [0, 1]\n#", "assert possibleRemainders(7) == [0, 1, 2, 4]\n#", "assert possibleRemainders(5) == [0, 1, 4]\n#", "assert possibleRemainders(3) == [0, 1]" ]
def possibleRemainders(n: int) -> list[int]:
[ "math" ]
from code import possibleRemainders
lbpp/python/128
python
rank_employees_by_importance
An employee list contains 3 values: the id of the employee (int), its importance (int), and the set of subordinate employee ids. The 'aggregate importance' of an employee is defined as the sum total of their own importance and the 'aggregate importance' of each of their subordinates. Write a Python program that returns...
class Employee: def __init__(self, id: int, importance: int, subordinates: object, aggregate_importance: int=0) -> None: self.id = id self.importance = importance self.subordinates = subordinates self.aggregate_importance = aggregate_importance def determine_each_employee_aggregat...
eJzFkr8KwjAQhwV9kEMXhSA2TbO56eqig2BKqBpBtKk0dRARfAh9X89Ua+s/RBAzpV+uuft9ZF85ynLJruEQN9VZHIUwiaYK5uEqihOIA72QKlwto41SRo43Mj0I9EQJLXQNBt3+QOisBNowEhpwjVoEPAJbhwDd+eQCnRS65IYoARcRyyH8xsKtl0MMr0HEc8izVUYl9UbGeJH5QsfKrJcJzvUuSz3jDaEDY9Q5++XHto3i2P7MzoqNuX8NL7u9znciXCsC2IOK8/33Moox0zmK7IUO9hMd1DbjmZG/66Af6qC/fR38iY7qoXkC1yf6...
[ "employees = [\n [0, 5, {1, 2}],\n [1, 5, {3,}],\n [2, 3, {4,}],\n [3, 1, {5,}],\n [4, 2, {6,}],\n [5, 1, set()],\n [6, 1, set()],\n]\nresult = rank_employees_by_importance(employees)\nassert result == [0, 1, 2, 4, 3, 5, 6]", "employees = [\n [0, 5, {1, 2}],\n [1, 3, {3, 4}],\n [2, 3...
def rank_employees_by_importance(employees: list[int|set[int]]) -> list[int]:
[ "tree", "recursion", "hashing", "maps" ]
from code import rank_employees_by_importance
lbpp/python/129
python
red_and_green
You are given an acyclic graph of nodes and directed edges where each node contains a list of k (<=8) colors (which are all either Green or Red, which are signified as 'G' or 'R'). You are given the starting node and destination node. You start at the starting node and adopt the sequence of colors in the starting node....
class Node: def __init__(self, sequence: list[str]): self.sequence = 0 if sequence[0] == 'G': self.sequence = 1 for i in range(1, len(sequence)): if sequence[i] == 'G': self.sequence = self.sequence | (1 << i) def get_num_ones_in_integer(num: int) -> ...
eJxrYJnKw8oABhGsQIZSWlF+rkJyfkqqQmZuQX5RiUJ6akl8bn5xSXx6UWpqXrGOgh9QMiYvJk9ZIcQ1OCQmL89QwRYsqBGtHqSuo6DuDiKQWbGaQFVGCFUYCsAssCpjNFUYBFiVCZqNGARYlSk2s4LQbEwsLk7F9KVGtEaeoU6ekaaORp6RTp4xiDbWyTMB0SY6eaZQcVPNWB0FoEIFIEvB1lbBGBYq8a5+LthDCMMRCF+NhBAyJTeEsHmSYIBh8zPB8CMrOLFpIhi6tA5sc8KBPeIyLIQ2gYeUCWayVJqiBwDud0GT
[ "n1 = Node(['R', 'G', 'R', 'G', 'R'])\nn2 = Node(['G', 'R', 'G', 'R', 'G'])\nn3 = Node(['G', 'G', 'G', 'G', 'G'])\nn4 = Node(['R', 'R', 'R', 'R', 'R'])\nn5 = Node(['G', 'G', 'R', 'R', 'G'])\nassert get_most_greens([(n1,n2),(n2,n3),(n3,n4),(n4,n5),(n2,n5)], n1, n5) == 3", "n1 = Node(['G', 'R', 'R', 'G', 'G'])\nn2 ...
def get_most_greens(edges: list[tuple[Node, Node]], start: Node, end: Node) -> int:
[ "graph", "traversal", "bit manipulation" ]
from code import get_most_greens, Node
lbpp/python/130
python
reg_expression_dates
Create a function in Python that uses a regular expression to match and capture all dates in the following format: * dd-mm-yyyy (dd represents day between 1 and 31, mm represents month between 1 and 12, yyyy represents year between 2000 and 2099) * dd-mm-yy (dd represents day between 1 and 31, mm represents month betwe...
import re def find_all_dates(text: str) -> list[str]: pattern = re.compile(r"(\b(0[1-9]|[12][0-9]|3[01])-(01|03|05|07|08|10|12)-(\d{2})\b|"+ r"\b(0[1-9]|[12][0-9]|3[01])-(jan|mar|may|jul|aug|oct|dec)-(\d{2})\b|"+ r"\b(0[1-9]|[12][0-9]|30)...
eJydk81KxDAUhbuo73GJGwUr+dFiFrNztm6chWCk1GkKAzOpTOcBfAh9XMH0J7mJHZA2dHFyuHz35Cb9TL/Ti6RfLz9pkpD62Bxg21QadoeP5niCemeqotzvi6o86VYZZS5hs37eKFO2rZ4UXCnCeNZ/wJgTdBCKXMNqBa/KgF1YqciNt9jUooH15voX66fH/7OIHsdp0Dvy5uMqve2OVLdtHSEHfy5xPCKXGR0igZcC+ANKmdX63VeMui9xWhFlXB7k2aF1fE8a94jzBciZOZShmY/ug2NsDI2Ru0bxa3Cc4OodKLQcMi5zyEVPhN7Z...
[ "assert find_all_dates(\"12-12-12 11-12-12 10-12-12\") == [\n \"12-12-12\",\n \"11-12-12\",\n \"10-12-12\",\n]", "assert find_all_dates(\"31-12-2012\") == [\"31-12-2012\"]", "assert find_all_dates(\"31-dec-12 fssf\") == [\"31-dec-12\"]", "assert find_all_dates(\n \"29-02-2012 29-02-2013 28-02-2013...
def find_all_dates(text: str) -> list[str]:
[ "regex" ]
from code import find_all_dates
lbpp/python/131
python
remove_cycle
Given a directed weighted graph with exactly one cycle, write a Python function to determine the total sum of the weights of the entire graph after removal of the lowest weighted edge that would cut the cycle. All weights are guaranteed to be positive values. The function should exception a List of Lists representing t...
class Node: def __init__(self, value: int): self.value = value self.outgoing = [] self.incoming = [] class Edge: def __init__(self, source: Node, target: Node, weight: int): self.source = source self.target = target self.weight = weight def dfs(node: Node, vis...
eJxrYJn6lYkBDCLeARlKaUX5uQrJ+SmpCpm5BflFJQpFqbn5ZanxyZXJOakxeTF5ygohrsEhMXmJxcWpaNIa0dGGOgpGOgqGsToK0UDaGMgDMYE0UMI4NlZTwdZWwRRmSLyrnwshA01gphBltDmVjDZGGG1EDaONEUYb0s5oE0yjLalstCk02IG0GYJpDlULFLKA+tAMagLEGYYWpLvDBO4OU6zuMMPqDguEOywx3WGMEh5KU/QAQnnNIg==
[ "assert remove_cycle([[1, 2, 1], [2, 3, 2], [3, 1, 3]]) == 5", "assert remove_cycle([[4, 3, 2],[1, 2, 1], [2, 3, 2], [3, 1, 3]]) == 7", "assert remove_cycle([[4, 3, 2],[1, 2, 1], [2, 3, 3], [3, 1, 2]]) == 7", "assert remove_cycle([[4, 3, 2],[1, 2, 3], [2, 3, 1], [3, 1, 2]]) == 7", "assert remove_cycle([[4, ...
def remove_cycle(edges: list[list[int]]) -> int:
[ "graph" ]
from code import remove_cycle
lbpp/python/132
python
remove_duplicates
Let `array` be a sorted list of two element tuples, representing the students in a class. Each tuple consist of a letter and a number. The letter signifies the group the student belongs to, and the number signifies the student's strength. The array contains multiple groups with each group having one or more students. W...
def remove_duplicates(array: list[tuple[str, int]]) -> list[tuple[str, int]]: k = 0 prev_grp = None insert_idx = 0 next_hole = None for idx in range(len(array) - 1): curr_grp, curr_max = array[idx] if curr_grp == array[idx + 1][0]: if prev_grp == curr_grp: ...
eJxrYJl6k5kBDCIuARlKaUX5uQrJ+SmpCpm5BflFJQpFqbn5ZanxKaUFOZnJiSWpxTF5MXnKCiGuwSExeYlFRYmVCrYK0RoxSokxSjoKRpo6CkB2EjrbBIltgcQ2NIBwksEcJLYxhF2EzjZBYltqxsbkpVYUpCaXpKbE55eWFJSW4HIMyZZiWJSYXFKamIOwBiNgNMChoQlUWVycCgw5DJfZKqCYAQvGeFc/FyKDlHJfDN/gUk9Uh7kVzDRCMI0hzCSQAlM40wjBhCpIRmgDMU0QTFMDXIGHxy7sFmCYStOQUpqiBwB0NhUM
[ "array = [(\"a\", 2), (\"b\", 2), (\"b\", 4), (\"b\", 8), (\"b\", 10), (\"c\", 1), (\"c\", 3), (\"r\", 3), (\"r\", 4), (\"r\", 9)]\nexpected_output = [(\"a\", 2), (\"b\", 8), (\"b\", 10), (\"c\", 1), (\"c\", 3), (\"r\", 4), (\"r\", 9)]\nactual_output = remove_duplicates(array)\nassert expected_output == actual_outp...
def remove_duplicates(array: list[tuple[str, int]]) -> list[tuple[str, int]]:
[ "array" ]
from code import remove_duplicates
lbpp/python/133
python
remove_every_x_letter
Write a python function `remove_every_x_letter(s: str, x: int) -> str` that will remove every x letter from a string
def remove_every_x_letter(s: str, x: int) -> str: return "".join([s[i] for i in range(len(s)) if (i + 1) % x != 0])
eJydjjELwjAQhRX8IY+4KIiD3YRudujiYgeHQAh6EiHphTQWu/kj9P/aCB06OOhNd+/eve8es9d2OvnUMesbcQnscOIz4eo8h4hAjltS1FLo1F1ZipGCrGU9R1UcKlnrpqFvvoUUhqxlKVbYLJHn6IU0Dueq2O9+i0IJ7ZBWMNr7DpHREKHjW6JkA4Usl3CgAOM9Yu9BcvwHHv0/DhHP9RtS8Wrf
[ "assert remove_every_x_letter(\"hello\", 2) == \"hlo\"", "assert remove_every_x_letter(\"hello I am very happy to see you\", 3) == \"heloI m er hpp t se ou\"", "assert remove_every_x_letter(\"h\", 2) == \"h\"" ]
def remove_every_x_letter(s: str, x: int) -> str:
[ "string" ]
from code import remove_every_x_letter
lbpp/python/134
python
return_a_tricky_string
Write a python function that returns a string with the following literal content "I can't believe it's not butter" including the double quotes.
def return_a_tricky_string() -> str: return "\"I can't believe it's not butter\""
eJxrYJkax8gABhHhQIZSWlF+rkJyfkqqQmZuQX5RiUJRaklpUV58YnxJUWZydmV8MZDOS4/Ji8lTVghxDQ6JyUssLk7FqVBDU8HWViFGKSYmRslTITkxT71EISk1JzO1DGhDiXqxQl4+UKC0pCS1CKQECKHmxrv6uQwXO5Sm6AEAnVF5fA==
[ "assert return_a_tricky_string() == \"\\\"I can't believe it's not butter\\\"\"", "assert return_a_tricky_string() == \"\\\"I can't believe it's not butter\\\"\"", "assert return_a_tricky_string() == \"\\\"I can't believe it's not butter\\\"\"" ]
def return_a_tricky_string() -> str:
[ "string" ]
from code import return_a_tricky_string
lbpp/python/135
python
robbing_houses
There are a number of houses, each with a certain amount of money stashed. Houses can be connected through an alarm system such that if you rob two houses that are connected to each other, the alarm will go off and alert the police. You are given a list of non-negative integers representing the amount of money of each ...
def dfs(nums: list[int], index: int, graph: dict[int, list[int]], visited: set[int], current_score: int) -> int: if index == len(nums): return current_score score_without = dfs(nums, index+1, graph, visited, current_score) for i in visited: if i in graph and index in graph[i]: re...
eJxrYJk6g5EBDCImAhlKaUX5uQrJ+SmpCpm5BflFJQq5iRXxibn5pXkl8UX5SUmpKTF5MXnKCiGuwSExeYnFxanY1GhEm+goGOsomOooGMbqKERHG+ooGIEYBiA6VlPB1lbBAmZMvKufCxlGGoAYEKMMDcg3S0fBHOo2kIkmIIYRiIaabEp9k4E0LDiAfGMobQqz0RjZRqUpegDDN3gj
[ "assert max_amount_robbed([4, 3, 5, 1], [[1, 2], [0, 2]]) == 8", "assert max_amount_robbed([4, 3, 5, 1], [[0, 1]]) == 10", "assert max_amount_robbed([4, 3, 5, 1, 7, 2], [[0, 4], [2, 4]]) == 15", "assert max_amount_robbed([4, 3, 5, 1, 7, 2], [[0, 4], [2, 4], [1, 2], [2, 3], [2, 5]]) == 13" ]
def max_amount_robbed(nums: list[int], connections: list[list[int]]) -> int:
[ "backtracking", "graph" ]
from code import max_amount_robbed
lbpp/python/136
python
rotate_puzzle_piece
You are developing a game that involves puzzle mechanics where players need to rotate pieces to fit into a specific pattern. The puzzle pieces are represented as numpy arrays of dimension [2 x num_pieces]. Each column corresponds to the [x, y] coordinates. In order to solve a particular level, a player needs to rotate ...
import numpy as np def rotate_puzzle_piece(puzzle: list) -> np.ndarray: rotationMatrix = np.array([[0, -1], [1, 0]]) return np.dot(rotationMatrix, puzzle)
eJyljkELgjAYhiP6IR92UVBBMzx5y2sEeQg2kWULBJ0y50FP/Yj6v82leJFAHBsb297nfV67T7bdqHG7y4P25GUBafmgkBVVyQXwUhBBk6rpulxuGU0pZsMba4qqBVIDqzDDbA9ReI0wE7QWF/UfAkDIMcGNTUAHE7w4xozUNZVhfYasT1EDgkBybcI5aXWELBm3vJ6jeLFh2CTPdWOsTcLz6a+Cms4AGC5W6EiCWm6/Rq2hY5mcjBwnsx9glVavpHAjeaFPH/VXOPiqe75Ve9tfhSPFMA==
[ "testPuzzle = [[1, 2], [3, 4]]\nassert (rotate_puzzle_piece(testPuzzle) == np.array([[-3, -4], [1, 2]])).all()", "testPuzzle = [[1, 2, 2, 1], [1, 1, 2, 2]]\nassert (rotate_puzzle_piece(testPuzzle) == np.array([[-1, -1, -2, -2], [1, 2, 2, 1]])).all()", "testPuzzle = [[2, 5, 1], [1, 2, 1]]\nassert (rotate_puzzle_...
def rotate_puzzle_piece(puzzle: list) -> np.ndarray:
[ "list", "math" ]
from code import rotate_puzzle_piece import numpy as np
lbpp/python/137
python
salary_raises
You are given a 2d numpy where each row represents the following values: [Employee ID, Years of Experience, Age, Current Salary (in thousands)]. Write a python function salary_raises(data: np.ndarray) -> np.ndarray that returns a modified version of the array where each employee that has 10 or more years of experience ...
import numpy as np def salary_raises(data: np.ndarray) -> np.ndarray: condition = (data[:, 1] >= 10) & (data[:, 2] < 40) indices = np.where(condition) data[indices, 3] *= 1.5 return data
eJztlL9qwzAQxjt06GMc6ZKACJYdO/aQrYFO7dAMhboY0ShgsGVXsgdvfYj2ffvJcUq1dHBp6D9hOHG/O/n0+cNPpy/XZyf9ur3EZrLTVUkP1VZSXtaVbsiIQugu0yI30qRqyKq2rDsShlSdqlSd02Z9swFVeZOLglbIz4XWopumirDu9qHfckbcYxQkiL53z94hn1HMaOHZCpcEthhNwDxw0YJRCIKmxAU2y8hHiFwQMVqCAXDuEqQ50qGdIHSRHQynISxdgHvgCeyEXugQe028y8epyRs5xG3T1XIFnXZFJRoeIT1LlZamLRoI6Og+...
[ "initial = np.array(\n [\n [1, 10, 39, 120],\n [2, 8, 40, 100],\n [3, 12, 38, 130],\n [4, 5, 30, 90],\n [5, 3, 25, 60],\n [6, 7, 35, 110],\n [7, 15, 50, 150],\n [8, 4, 28, 70],\n [9, 9, 33, 105],\n [10, 6, 27, 95],\n ],\n dtype=np.float1...
def salary_raises(data: np.ndarray) -> np.ndarray:
[ "numpy" ]
from code import salary_raises import numpy as np
lbpp/python/138
python
shortest_matching_subspan
When a document is retrieved by a search query, our search engine would like to highlight the section of the document most relevant to the query. Given the document and the query, write a Python function to find the smallest possible span of the document that contains all the tokens in the query where the order of quer...
from collections import Counter def shortest_matching_subspan(query, document): query_tokens = query.split() document_tokens = document.split() query_counter = Counter(query_tokens) window_counter = Counter() left = 0 min_span = (-1, -1) min_span_len = float('inf') for right in range(l...
eJy9kr9qwzAQxgvtgxzqkoAoMSkNHbI1a5Zm6CAwsq1EAktKfOfBWx6ifd9enLp/hqRE0J6EdOg+nX58aH/ztr++6uOl40Ssm+ihjJUB57exIUDLq0HKvabSurDJsS1wq4PicQurxfNKBY1ozmlHSpB1CDw17FrTdEpI+H5YxbL1JhCQ1cQAgbQLn2pYxwa+xIc3lBjDfA4jFYDjQR73bMLJeADLF8unSyD7FqmoRa3tSVpuwFw98ExCliUj/gZ3BEgzcfJh4vRPPBwqGL2hwx1Ip5aDmZmE+/9FRVfXHVStL9KpH/kLTH9gi9e7d4O4...
[ "assert shortest_matching_subspan(\"this is a query\", \"this is a document that contains a query for this is a test\") == (\n 6,\n 10,\n)", "assert shortest_matching_subspan(\n \"this is a query\", \"this is a document that contains blah query for this is a test \"\n) == (7, 11)", "assert shortest_mat...
def shortest_matching_subspan(query, document):
[ "string" ]
from code import shortest_matching_subspan
lbpp/python/139
python
shortest_root_to_leaf_path
Write a class TreeNode which contains 5 variables: val (int), left (Optional[TreeNode]), right (Optional[TreeNode]), leftTime(int) and rightTime (int). Given an integer targetTime and the root of a binary tree (represented as a TreeNode), where each node represents a place and the edge between two nodes has a value whi...
class TreeNode: def __init__(self, val=0, left=None, right=None, leftTime=0, rightTime=0): self.val = val self.left = left self.right = right self.leftTime = leftTime self.rightTime = rightTime def shortestRootToLeafPath(root: TreeNode, targetTime: int): if not root: ...
eJy1ks9LwzAUxz3o3ZvXUC8blOE2J3joYU1/DaSI9iAYkTKzreASaePdP0L/X1/SJmvmqlOwjDXv8/LtS77vvR1+nBwdqOfuGBbOouRrNOdPFBXrF14KlJWUphC7qFpBTCtxw7nI+BXNF9e5WBFG2CkoWCXK17ko2BIJkCAGmoqwKfLMJ3rEmRKnT5hvQ19BbEOsYGDDQMHQhqGCkQ0jBWMbxgomNkwUnNlwpmB9tyy8zeAig2e6ELDLl+uyWK5kgHUiK9YU4rFJNmAkv+FrbSDXWhvqRLP1wiQbMJFabPZHJtgIwAyTj03Qrh3p2ole...
[ "A.left = B\nA.right = C\nA.leftTime = 3\nA.rightTime = 2\n\nB.left = D\nB.right = E\nB.leftTime = 6\nB.rightTime = 5\n\nC.right = F\nC.rightTime = 6\n\nE.right = G\nE.rightTime = 2\n\nF.left = H\nF.leftTime = 2\n\nH.right = I\nH.rightTime = 2\n\nassert shortestRootToLeafPath(A, 9) == [\"A\", \"B\", \"D\"]", "C =...
def dfs(node, currentSum, path, pathLength):
[ "tree", "traversal" ]
from code import TreeNode, shortestRootToLeafPath # constructing tree nodes A = TreeNode("A") B = TreeNode("B") C = TreeNode("C") D = TreeNode("D") E = TreeNode("E") F = TreeNode("F") G = TreeNode("G") H = TreeNode("H") I = TreeNode("I")
lbpp/python/140
python
sort_messages
Write a python function "def sort_messages(message_list: List[Dict[Literal["text", "author", "date"], Any]) -> List[str]" that sorts all the messages in the message_list. The three fields of each messages are: text (str), author (str) and date (datetime.datetime). Messages should be sorted w.r.t. author first (accordin...
from typing import Any, Literal def sort_messages(message_list: list[dict[Literal["text", "author", "date"], Any]]) -> list[str]: urgent_messages = [] other_messages = [] for message in message_list: if "urgent" in message["text"].lower(): urgent_messages.append(message) else: ...
eJztVl9r2zAQ70Nf+i0u7sNaMCX1ygaDEgo1LaUtZXVhMI0g4qstsKViKW1DKexDbN9jb/t6U6zEU2c5UbKxp5pgx3e6+9397k/ydfP7z62N+vr0Q38JbitRwkikCKy8E5UCqW/DEqWkGUrCa31KFSpWNmfm74QTvg1JfJ0QPjMZFkwqOITPhIO+nkig8FGR4AOQ4BQnkIsHYBKYgkwwng1IEGoNHatcVOZUkouSSiOfAk2lc8CdqB/th6A/0e5z2AHB1BsJZ6JKKW97t+Xd3t92eGeh8X5Fx0Wv12u7nyqWOX9XO/9COJUS/2R8x+Zx...
[ "message_list = [\n {\"text\": \"Hey how is it going?\", \"author\": \"Thomas\", \"date\": datetime(2021, 1, 2)},\n {\"text\": \"Hey it's Jordan\", \"author\": \"Jordan\", \"date\": datetime(2021, 1, 3)},\n {\"text\": \"Hi, it's Paul!!!\", \"author\": \"Paul\", \"date\": datetime(2021, 1, 6)},\n]\nassert s...
def sort_messages(message_list: list[dict[Literal["text", "author", "date"], Any]]) -> list[str]:
[ "date", "list", "string", "dictionary", "sorting" ]
from code import sort_messages from datetime import datetime
lbpp/python/141
python
split_camel
Write a python function "def split_camel(name: str) -> str" that splits a Camel Case variable name and puts every word in lower case. Write it in Python.
def split_camel(name: str) -> str: output = "" for i in range(len(name)): if name[i].isupper(): output += " " output += name[i].lower() else: output += name[i] return output
eJyVj0EKwjAQRRU8yFA3uvEG3VmXddEKLgIlNlMoNJOSScGlVxAUPK5pTYuupFkN//+8+XNbPV/LxfDOdz9ElTUaSqMQat0a64DbpnZFKTU2ggStgUywGAhRoerFPMlyQZIZf79sRGSsQpt2+oJWRFuIYwgaUBBHQJGk+z8wdp1CcnzwNU9UO1SZkw55Io8BGA7phghwyMxYpOX10/lYZQE57fBe6A6mAp7sGfhGskv9PDF7AWhQvjHRY/cGHpqPFw==
[ "assert split_camel(\"orderNumber\") == \"order number\"", "assert split_camel(\"studentsFromUnitedStates\") == \"students from united states\"", "assert split_camel(\"maxNumberOfStudents\") == \"max number of students\"", "assert split_camel(\"lastName\") == \"last name\"" ]
def split_camel(name: str) -> str:
[ "string", "loop" ]
from code import split_camel # no imports needed
lbpp/python/142
python
split_import_and_code
Given a Python script as string input, remove all import statements and return the script and imports as separate strings. Explicitly handle multiline imports. For example, the script """import numpy as np\nfrom string import (\n template,\n)\ndef foo():\n return True""" should return ("""import numpy as np\nfrom str...
import re def split_import_and_code(script: str) -> tuple[str]: pattern = re.compile( r"^\s*(from\s+\w+\s+import\s+[\w ,]+;*|import\s+[\w, ]+;*|from\s+\w+\s+import\s+\([\s\w\s,.]+\))", re.MULTILINE ) imports = pattern.findall(script) non_import_code = pattern.sub("", script) non_import_...
eJzNU8FKxDAQ9aD/EdbDtlD6AcLe3JuI4AoeAiHbpruDbRKSqaAnP0J/xJt/5zRN1kVcFcXFpIG8mcnk9WXm4fDp5eggjOtn2kwaZzpWmVox6KxxyLxtAcUIhNS1GJxcc33MFvPLBde+cmCRzRifDDMe031n75j0TFvOdcjq0YFepbwZmRkNVJ1tJaqCcE6rVg1rjMnykxjgFPZOs4Xr1XgD19J7tYtaNvLJ2WxGd4QMvyU1KVKez8kVQ3DURczPTz/QaMNomIFATdcgdBu9E04ErcR1C8vkviCYXHhnt7ifgceCXWkwmgKi0ZIs9L/0...
[ "script = \"\"\"import numpy as np\\nfrom string import (\\n template,\\n)\\ndef foo():\\n return True\"\"\"\nassert split_import_and_code(script) == (\n \"import numpy as np\\nfrom string import (\\n template,\\n)\",\n \"def foo():\\n return True\",\n)", "script = (\n \"\"\"from datetime imp...
def split_import_and_code(script: str) -> tuple[str]:
[ "string", "regex" ]
from code import split_import_and_code
lbpp/python/143
python
sub_images
For an image processing problem, you are given a black and white image represented by a mxn matrix of binary digits and a list of sub-images also represented by binary digits. Write a Python function to return an array of booleans equal to the length of the list of sub-images that indicates which sub-images were found ...
def image_filters(image: list[list[int]], sub_images: list[list[list[int]]]) -> list[bool]: result = [] for sub_image in sub_images: found = False for i in range(len(image) - len(sub_image) + 1): for j in range(len(image[0]) - len(sub_image[0]) + 1): found_sub = True ...
eJxrYJmaysMABhFxQIZSWlF+rkJyfkqqQmZuQX5RCZBKTE+NT8vMKUktKo7Ji8lTVghxDQ6JyQNLKNgqREcb6CgYgpEBGBkic2N1YvIUYACq0oAGKom3nUYqDQedO2Nj8opLk+LB8WQIjiioPIoZYHMISiCbZUSRWajuMibfLAN0dxWDzEL4WEcB4WIktjFQS2JxcSp60tYA85AUFmsq2AINDCkqBYq6JeYUw6hYWB6Id/VzGc0Po/kBOdIxtUBjDrcE1vxggMss/BL0yg8IcjQ3jOYGEnIDrBIYVrkBWjsM2+yAzCDGTIIqR7MDihZq...
[ "image = [[0, 1, 1, 0, 0, 1, 1, 1, 0, 0],\n [0, 1, 0, 0, 0, 1, 1, 1, 0, 0],\n [0, 1, 0, 0, 0, 1, 1, 1, 0, 0],\n [0, 1, 1, 0, 0, 1, 1, 1, 0, 0],\n [0, 1, 1, 0, 0, 1, 1, 1, 0, 0],\n [0, 1, 1, 0, 0, 1, 1, 1, 0, 0],\n [0, 1, 1, 1, 0, 1, 1, 1, 0, 0],\n [0, 1, 1, 0,...
def image_filters(image: list[list[int]], sub_images: list[list[list[int]]]) -> list[bool]:
[ "matrix" ]
from code import image_filters
lbpp/python/144
python
subsets_divisible_by_x
Given a positive integer N, write an efficient Python program to return the number of subsets in a set of numbers from 1 to N whose sum of elements is divisible by 2.
def divisible_subsets(N: int) -> int: return (2**N)//2 # using integer division to avoid overflow for large values of N
eJxrYJkawMgABhGeQIZSZm5BflGJQklmbmpMXlpRfq5Ccn5KqgJUOCWzLLM4MyknNb64NKk4taQ4Ji8mT1khxDU4JCYvsbg4FZsaDUNNBVtbBUOYynhXPxcidJmAdVlg11VcklhUEg9ypYIt2LF6IEJDMyavKLW4NKcEKIrFHQYGmgoKcCuRtCnoKiCZaKNgmKprAlcHM9FWwczY2MLI1NjAwNDQBIjMDQzMTSyMTQ3NDIzMLFBcqjRFDwD37m/w
[ "assert divisible_subsets(1) == 1", "assert divisible_subsets(4) == 8", "start_time = time.time()\nresult = divisible_subsets(100) \nassert time.time() - start_time < 1e-4\nassert result == 633825300114114700748351602688" ]
def divisible_subsets(N: int) -> int:
[ "math" ]
import time from code import divisible_subsets
lbpp/python/145
python
sum_items_with_prices
Write a python function `sum_items_with_prices(items: List[dict]) -> Tuple[float, List[dict]]` that takes a list of dictionaries where if a dictionary has the key "price" it will map to a float and returns a tuple consisting of the total of all present "price" values and a list of all the dictionaries in `items` withou...
def sum_items_with_prices(items: list[dict]) -> tuple[float, list[dict]]: total_price = 0.0 unpriced_items = [] for item in items: if "price" in item: total_price += item["price"] else: unpriced_items.append(item) return (total_price, unpriced_items)
eJxrYJkaxMQABhHeQIZSWlF+rkJyfkqqQmZuQX5RiUJxaW58ZklqbnF8eWZJRnxBUWZyanFMXkyeskKIa3BITF5icXEqLnUa0bGaCra2ChoGegY6CkAOTFu8q58LsUZUxyjlJeamxihZKcQoFSTmlRTHKOmAmCB5kKihnpFxrY4Cirri/ORsdHVGega1UPcYA7VQx0HFGZlFJTFKGPZn5AODSQlmX0yeAhCAQgHCIs0MoCaaORRngKK4HCSC1+kYblSaogcAy1K/ag==
[ "assert sum_items_with_prices([]) == (0.0, [])", "assert sum_items_with_prices([{\"name\": \"pants\", \"price\": 1.23}, {\"name\": \"socks\", \"price\": 2.0}]) == (3.23, [])", "assert sum_items_with_prices([{\"name\": \"shirt\"}, {\"name\": \"shoes\"}]) == (\n 0.0,\n [{\"name\": \"shirt\"}, {\"name\": \"s...
def sum_items_with_prices(items: list[dict]) -> tuple[float, list[dict]]:
[ "list", "dictionary" ]
from code import sum_items_with_prices
lbpp/python/146
python
swap_ith_node_at_kth_level
Write a class TreeNode with 3 attributes: val (int), left (Optional[TreeNode]), and right (Optional[TreeNode]). Then write a python function to swap node values of the ith node at the kth level from the top and the ith node and kth level from the bottom of a binary tree. Note that the height of a leaf node should be 0.
from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None) -> None: self.val = val self.left = left self.right = right def swapIthNodeAtKthLevel(root: TreeNode, i: int, k: int) -> TreeNode: toSwap = [] h = height(root) queue = deque([(root,...
eJzNVF1LwzAU9UH8HZf5smIdy7pvqCC4B1H6oH0QuiLFpjbQJSON9UnwR+j/NU3X0Zq+ZCIsLWw3957Tk3Nv+3n6/XF2otZTIf/0Es428MJiDGSzZVyAzzH2ZGxD/h5tb0VaBtfiTqT3uMDZmpZXjBMglPEYc59HBeZ5lPU5Y2K5x1tweQUZyUVAqAiXawpykQTKKiA5eIzi3W65OBZvnEIQVlu7sPMZgwwnwoILCFRURFkog+5STl5TYVWiz8FfPfprqhS4e6F9ZFV7ireZGNUJxdLMOE2Ihhu3shp40qLV0NN2WoPP1HHK5mxx/FCd...
[ "root = TreeNode(1)\nroot.left = TreeNode(2)\nroot.right = TreeNode(3)\nroot.left.left = TreeNode(4)\nroot.left.right = TreeNode(5)\nroot.right.left = TreeNode(6)\nroot.right.right = TreeNode(7)\n\nswappedRoot = swapIthNodeAtKthLevel(root, 2, 2)\n\nassert inorderTraversal(swappedRoot) == [4, 2, 5, 1, 6, 3, 7]", "...
def height(root: TreeNode) -> int:
[ "tree" ]
from code import TreeNode, swapIthNodeAtKthLevel def inorderTraversal(root: TreeNode) -> list[int]: if root is None: return [] return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right)
lbpp/python/147
python
swap_outer_inner_nodes
Given a perfect binary tree, write a python program to swap the outer nodes with the inner nodes of its left and right sub-trees. The inner nodes of a binary tree includes the sequence of nodes starting from the root node to the rightmost node of its left subtree, and the nodes from the root node to the leftmost node o...
class TreeNode: def __init__(self, val: int = 0, left: "TreeNode | None" = None, right: "TreeNode | None" = None) -> None: self.val = val self.left = left self.right = right def get_path(node: TreeNode, left: bool = True) -> list[TreeNode]: path = [] while node: path.append...
eJztVc1u2zAM3mHXvQPRXizMSSOladZg2Wm99rIeBjhGYMRKq8KVPVlpr3uI7X2nnzimHDtor0MVwJFIfuQnipR+f/x7+emDGz9HZnK2VeUTbMqcg3iqSqXhTnF+a9Yx1C9ZtS53mqu1kNJ8pRHXK7mHFAXfaFHKukHm/NeOr6T95XwLBX/mxbpUuUFqlT1zVWdFpMpSLw5BCIy+QSFqnbiPkDpNFysJZogtWFsQNdyWku+ldiiud0pCktpIXlDvCg1LJ7ICw2PHzdoxihIXNIYJSUkDeXkQBfd2yLN0+3bEDdppx1VZFXyrowN0T67g...
[ "root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))\ninput = level_order_traversal(root)\nswap_outer_inner_nodes(root)\noutput = level_order_traversal(root)\nassert len(input) == len(output)\nassert input[0] == output[0]\nassert input[1] == output[1]\nfor i in range(2, ...
def swap_outer_inner_nodes(root: TreeNode):
[ "binary tree" ]
from code import TreeNode, swap_outer_inner_nodes from collections import deque def level_order_traversal(root: TreeNode) -> list[list[int]]: if root is None: return [] result = [] queue = deque([(root, 0)]) while queue: node, level = queue.popleft() if len(result) <= level:...
lbpp/python/148
python
tax_bracket_raise
You are given a list of salaries, a mapping between marginal tax rate and the income at which that marginal tax rate applies, a maximum marginal tax rate, and a target tax revenue. You can not increase any of the marginal tax rates beyond the rate of the maximum marginal tax rate. You should only increase a marginal ta...
def get_new_marginal_tax_rates( salaries: list[float], marginal_taxes: dict[float, float], max_tax_rate: float, target_revenue: float ) -> dict[float, float]: # sort marginal_taxes marginal_taxes = dict(sorted(marginal_taxes.items(), reverse=True)) # iterate through marginal_taxes dictionary current...
eJxrYJnaz8wABhEdQIZSWlF+rkJyfkqqQmZuQX5RiUJ6akl8Xmp5fG5iUXpmXmJOfEliRXxRYklqcUxeTJ6yQohrcEhMXmJxcSpexRrRhgYgoKNgBKWNwXSsjkK1gZ6hlQJQxEDPyEoBpsxAz9gKqrYWxDPRgUppKtjaEqEH5rZ4Vz8XervTFJs7TWB6qOA0U+o6zRhZjwnlQWgOMcvQCOpcKN/YCMW5RjAbsTsZ5hYLuPtNgUYZm6C6H26IKeXBS0NnmxkjOduIoLOVpugBAKgo6mA=
[ "assert get_new_marginal_tax_rates([100000, 200000, 300000], {0.1: 0, 0.2: 100000, 0.3: 200000}, 0.4, 100000) == {0.1: 0, 0.2: 100000, 0.3: 200000}", "assert get_new_marginal_tax_rates([100000, 200000, 300000], {0.1: 0, 0.2: 100000, 0.3: 200000}, 0.4, 150000) == {0.1: 0, 0.4: 100000}", "assert get_new_marginal_...
def get_new_marginal_tax_rates( salaries: list[float], marginal_taxes: dict[float, float], max_tax_rate: float, target_revenue: float ) -> dict[float, float]:
[ "math", "lists", "dict" ]
from code import get_new_marginal_tax_rates
lbpp/python/149
python
test_sqrt_ratio
Write a python function that returns True if the square root of a number is strictly greater than the number divided by ten. For negative numbers, return False.
def test_sqrt_ratio(num: float) -> bool: # num/10 < sqrt(num) if and only if num != 0 and sqrt(num) < 10, # which is more simply: return 0 < num < 100
eJxrYJm6j5EBDCK2AxlKaUX5uQrJ+SmpCpm5BflFJQolqcUl8cWFRSXxRYklmfkxeTF5ygohrsEhMXmJxcWpmCo0dA01FWxtFdwSc4pTYYrjXf1cCGo0IFMfxL6QolLStFla6lmSp9PQgGynGhjokRs8QL04rFWaogcADN6XTQ==
[ "assert test_sqrt_ratio(-1) == False", "assert test_sqrt_ratio(0) == False", "assert test_sqrt_ratio(1) == True", "assert test_sqrt_ratio(99.9) == True", "assert test_sqrt_ratio(100) == False", "assert test_sqrt_ratio(100.1) == False", "assert test_sqrt_ratio(1000) == False" ]
def test_sqrt_ratio(num: float) -> bool:
[ "math" ]
from code import test_sqrt_ratio
lbpp/python/150
python
to_paragraph
Write a python function `to_paragraphs(paragraphs: List[str]) -> str:` that accepts an array of strings where each string in the array is a paragraph. Make each sentence end with a double space except the one at the end of each paragraph. Concatenate the paragraphs into a single string with each paragraph separated by ...
def to_paragraphs(paragraphs: list[str]) -> str: spaced_paragraphs = [] dots = [".", "!", "?"] for paragraph in paragraphs: i = 0 while i < len(paragraph) - 1: if paragraph[i] in dots and paragraph[i + 1] not in dots: paragraph = paragraph[: i + 1] + " " + paragr...
eJyVkcFOwzAMhhHiQX7KZZWQ32A3duiFC5VAWqbJa7O1qE2qJNu0Gw8Bb8aNl8Fd2aDVQMzKr1hOHH+xX67ePi4v9vb0Lk60dLZGZnONsm6sCwh23rDjleOm8Mooc4N08pAqw97r4floqqJCV5UlbK2rchXNYozHOEYP4cMz88n93blP3uJ/RZQ5p+hIGYj1a3ex1qbfbmsqSsA1GFtXBu0oQWU3Gs3aZGHNobSGCGlResjaaLf7aiebcI3HggN05TUyNkjgeUfyrWGFQ3q9g9eZNTmOZL3bs86Nu23fiD4ccBLvV77TgMr8CaRMfH5/...
[ "assert to_paragraphs([\"hello. world\"]) == \"hello. world\"", "assert to_paragraphs([\"hello. world\", \"hello. world\"]) == \"hello. world\\nhello. world\"", "assert (\n to_paragraphs(\n [\n \"I am a writer.I love punctuation.. This is very important! What else can I say.\",\n ...
def to_paragraphs(paragraphs: list[str]) -> str:
[ "string" ]
from code import to_paragraphs
lbpp/python/151
python
total_landmarks_visited_prime
In a certain region, there are m cultural landmarks numbered from 1 to m, connected by at least m-1 bidirectional pathways such that there is always a route from one landmark to any other landmark. It is observed that visitors have a preference for prime numbers: visitors move from landmark a to b if b > a and b is the...
from collections import defaultdict def is_prime(n: int) -> bool: if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def next_prime(n: int) -> int: prime = n + 1 while not is_prime(prime): prime += 1 return ...
eJytkr9qwzAQhwvtgxzp4sARIv+Vh2zJ2qUZCpExpnbBJJKCrXTuQ7TvW517CS3UgYC9fHeyfL9Pwh8PX+v7u+F5Wfli9tZZDa+2bqDVR9s5cNZVh/JQmVpX3b4v39u+dU2tjDKPsN08b5XRsIJQmcse3+4CgRDOC2XsyR1Pzi+NDAo0wmVxrkzV942PPX82TP4JKjdP67+h0b+hCEGIEE0SHo+Hi+XVdM8IISbGCAkxQUiJKUJGzBAkUSLkxBz90Em0xRVvOaYtWFuwtmDtkDUj1o+5H44xia284ZZ3dKsFAjEjCu69Vsq9WFIhzwUd...
[ "m = 2\nlandmarks = [(1, 2)]\noutput = total_landmarks_visited(m, landmarks)\nassert output == 2", "m = 3\nlandmarks = [(1, 2), (2, 3)]\noutput = total_landmarks_visited(m, landmarks)\nassert output == 4", "m = 10\nlandmarks = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]\noutput = t...
def total_landmarks_visited(m: int, edges: list[tuple[int]]) -> int:
[ "graph" ]
from code import total_landmarks_visited
lbpp/python/152
python
total_production
Create a Python function `total_production(production: pd.DataFrame) -> List[Tuple[float, float, str]]`. Each row of `production` is a tuple representing a production line with values `<day, line, gross_production>`. Calculate the net production per line (gross production of the line * 80% yield). If the net production...
import pandas as pd def total_production(production: pd.DataFrame) -> list[tuple[float, float, str]]: production["line"] = production["line"].replace({"Line A": "Line A+B", "Line B": "Line A+B"}) production["net_production"] = production["gross_production"] * 0.8 result = [] for line, group in product...
eJztlc1Kw0AQxz148yWGeEkwlDTNxlboQW09iRcLCt1Slm4qhSYbkngQEXwIfV93s02bSdOq6KFiwxDmY2dJZn//5PXwPTs6yK/7UDrGNBEhTAQPYBbGIskgExmbj+NE8MdJNhMRjRaFmEWcpSAt5lSmj2HQvx1QmcwYdOGZRiAvanD2RI0zGDZt0OYW1irMK4xoG9lF83wWBXm3TujktUzCOTXsteRFXfKyLvnv2lczfUhEmpZPFM+36ThOaSMXhy0U+SgiKGp6W4qVpe0vL608ztZdO8tQvfyLRHMqwYx5oycRvUpYGJgKVotGLE2D...
[ "data = {\n \"day\": [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5],\n \"line\": [\n \"Line A\",\n \"Line B\",\n \"Line C\",\n \"Line A\",\n \"Line B\",\n \"Line C\",\n \"Line A\",\n \"Line B\",\n \"Line C\",\n \"Line A\",\n \"Line B\...
def total_production(production: pd.DataFrame) -> list[tuple[float, float, str]]:
[ "string", "list", "pandas", "lambda function" ]
from code import total_production import pandas as pd
lbpp/python/153
python
total_revenue
Given an array of positive integers, where each integer represents the height in metres of an open oil barrel, that is filled to the brim, at a refinery. The refinery sells the oil at the rate of $1 per metre of barrel. The oil barrels are placed side by side and are not arranged in any particular order of height. Ther...
def totalRevenue(a: list[int]) -> int: n = len(a) b = [0] * n lmax = 0 for i in range(n): lmax = max(lmax, a[i]) b[i] = lmax rmax = 0 ans = 0 for i in range(n-1, -1, -1): rmax = max(rmax, a[i]) ans += min(b[i], rmax) - a[i] return ans
eJxrYJn6ggECep4opRXl5yok56ekKmTmFuQXlSiU5Jck5gSllqXmlabG5MXkKSuEuAaHxOQlFhenoklrRBvpKBjqKBjHairY2ioYwhTHu/q5ENAI1GUE0WVAoi6IjTAGkDSBcY3hZpohm6k0RQ8ACyBIww==
[ "assert totalRevenue([2, 1, 3]) == 1", "assert totalRevenue([1, 2]) == 0", "assert totalRevenue([1, 2, 1, 3, 2, 1, 2, 4, 3, 2, 3, 2]) == 6" ]
def totalRevenue(a: list[int]) -> int:
[ "list" ]
from code import totalRevenue
lbpp/python/154
python
total_sales
Write a python function "def total_sales(file_path: str) -> float" that access the daily sales dataset in a csv file, which contains information about unit price and quantity, and calculates the total revenue. The file contains the following columns: "order_id", "product_id", "unit_price" and "quantity". Include error ...
import csv def total_sales(file_path: str) -> float: with open(file_path, "r") as file: csv_reader = csv.DictReader(file) total_revenue = 0 for row in csv_reader: try: unit_price = float(row["unit_price"]) quantity = float(row["quantity"]) ...
eJytlNFu0zAUhrnggrfAMhJapS6qj5O2Qeod45IbJoQ0T1FIPS1SlwTHpeyOh4D3xf6bta7JmJCWSn/r/sfHR+fzyc+Xv9++eoHny2v3g9+Y9o5V7Vqz+q5rjWW2teWm6MuN7lUz/Ff131XjP2/Y5cWnS9Ws9Q2rjC6tLpx3dlNvdNGV9nbK1qUtJ+9Uw9yzq+0tazvdhAGK7xSfskbvNnWjV4orPmFlz3zIsM8/Lm2xM7XVhq38ItkvkGkyFjYEtLv+DDXsC/Y/hctwtd9ypXhr1toU9doXoXhn2vW2sof1tqlt0Zm60vv1t23Z2Nre...
[ "def create_csv(file_path, data):\n with open(file_path, \"w\", newline=\"\") as file:\n csv_writer = csv.writer(file)\n csv_writer.writerows(data)\n\n\ndata1 = [\n [\"order_id\", \"product_id\", \"unit_price\", \"quantity\"],\n [1, 1001, 10.99, 3],\n [2, 1002, 25.50, 2],\n [3, 1003, 15...
def total_sales(file_path: str) -> float:
[ "dictionary", "loop", "exception handling", "file handling" ]
from code import total_sales import csv
lbpp/python/155
python
travelling_salesman_problem
Implement the travelling salesman problem in Euclidean space. Given city names and their x and y coordinates, return the length of the shortest tour. The shortest tour would be an array of city names, beginning and ending in the same city, so that each city - except the start/end city - is visited exactly once and the ...
from __future__ import annotations class City: def __init__(self, name: str, x: float, y: float): self.x = x self.y = y self.name = name self.roads = [] def distance(a: City, b: City) -> float: return ((a.x - b.x) ** 2 + (a.y - b.y) ** 2) ** 0.5 class Road: def __init__(se...
eJzF0L0KwjAUBeCiPsglLhXSkDRKLTjq6qKD0JQS2yiF/kijzj6EPq2LrW0WETc1Gc7lksDHuQxuvb71PJt7z7LQripziMtEQZofyuoI6hRnaaJkER0reVZZlhb7SMtM6VwWor5DWC9Wa1FIrVX9Xm61/fGPHQi0FQiDQLKNuI1EoBBDEFAMtBlcDG6TvEunXjhuGI7AAcYJnfi+Nx3BDCihzDiixXL+BZOxGFtnMbq/ml76McqfmT4V1CIY4Yx7PyfUxTi8mRgG1lHGhI3ddxJ0JQ/gP+AN
[ "assert abs(euclidean_travelling_salesman([\"b\", \"a\", \"c\", \"d\"], [[0, 0], [2, 2], [3, 2], [-2, -2]]) - 13.059978) < 0.01", "assert abs(euclidean_travelling_salesman([\"b\", \"a\", \"c\", \"d\"], [[2, 2], [0, 0], [-2, -2], [3, 2]]) - 13.059978) < 0.01", "assert abs(euclidean_travelling_salesman([\"b\", \"...
def euclidean_travelling_salesman(cities: list[str], coordinates: list[list[int]]) -> float:
[ "graph", "traversal", "travelling salesman problem" ]
from code import euclidean_travelling_salesman
lbpp/python/156
python
triangle_circle
Given three 2D points with the same distance to the origin (0, 0), write a python code that figures out whether the triangle that is formed by these 3 points contains the origin (0, 0).
import math def calculate_angle(point: tuple[float, float]) -> float: return math.atan2(point[0], point[1]) def is_angle_in_range(angle: float, start: float, end: float) -> bool: if start <= end: return start <= angle <= end else: return angle >= start or angle <= end def does_triangle...
eJxrYJkax8gABhHhQIZSWlF+rkJuYkmGQmZuQX5RiUJxYVFJTB5YODk/JRUmnJKfWhxfUpSZmJeekxqfnJ9XkpiZF59flJmemRcDhMoKIa7BITF5icXFqQSUa2gY6ygYaOooaBjoKBiDaF2wgCbMlHhXPxcME/PyiTUVhcZvKH4DQUGhYaSpoK9gpKOgi8QDu9kQ4QldQ1R7lKboAQDqd3Cx
[ "assert does_triangle_contain_origin((3, 0), (0, 3), (-3, 0))", "assert not does_triangle_contain_origin((3, 0), (3, 0), (3, 0))", "assert does_triangle_contain_origin((sqrt(2) / 2, -sqrt(2) / 2), (-1, 0), (0, -1))" ]
def does_triangle_contain_origin( p1: tuple[float, float], p2: tuple[float, float], p3: tuple[float, float] ) -> bool:
[ "math" ]
from math import sqrt from code import does_triangle_contain_origin
lbpp/python/157
python
unify_card_number_transcript
The company XYZ developed a new automatic speech recognition system for telephone banking. The system’s goal is to transcribe a customer’s voice input of a debit or credit card number into a string of digits so that the bank can use it to retrieve customer information. Assume you are an engineer working on this ASR sys...
def word_to_digit(word): number_map = { "zero": "0", "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9", "ten": "10", "eleven": "11", "twelve": "12...
eJzFk7FOwzAQhhn6IKewwFDkpImTDN3owMJCBwZLUZpcGkuNXdlOoEw8BLwvTlyJqgNVFBBefNLv833+JL/PPvnsaljPG1t4lZINFLJE4M1eKgOt4NUhK3JVZqJtNqgyo3KhC8X3hgkmrmG9elozYVCbkwiWwDwfQqjsJQcQXKDdkG9rAzEBGoGpeZ+YFwkaOxS29n3mMZFrjRcG35xNu4XlMC8MSZrEhEaLICbuNseXrR7vL7FWslUnuEAhsXS46/AYcVuZWiFCAMSdSUDz18nQKU38ILTQlp6Ogx4p+Nf8kl7wGFRpbfUoTuC3UOvP...
[ "test_transcript = \"1 4 forty ninety eight 70 65 thirty two seventy 11\"\nassert unify_card_number_transcript(test_transcript) == \"1440987065327011\"", "test_transcript = \"1 four forty nine 6 8 twelve four five three 2 0 nine 8 six\"\nassert unify_card_number_transcript(test_transcript) == \"1449681245320986\"...
def helper(i, digits, temp, temp_sum):
[ "recursion", "string" ]
from code import unify_card_number_transcript
lbpp/python/158
python
unit_cost
Write a python function "production_cost(raw_material_cost: Dict[str,float], raw_material_usage: Dict[str,float], daily_production: List[int]) -> float" function that takes as input two dictionaries: one containing the cost of each raw material and the other containing the number of each raw material that are used to p...
def production_cost( raw_material_cost: dict[str, float], raw_material_usage: dict[str, float], daily_production: list[int] ) -> float: total_cost = 0.0 for production in daily_production: daily_raw_material_cost = sum( raw_material_cost[material] * raw_material_usage[material] * produc...
eJy1kkFrgzAUx3vot+glZJcWRJIYU91tW3vdpT0MmlLEOibUpBh3KoN9iO37Nkpcqw9kg/URjPwMf97vmc/xNx6PmnqZ2Bf8WuoCpXqfobw46rJCx1Lv39Mq12qXalNJ5XiRVG9SSXWH1svVWqrEmMxhPzfpQZtsKhWy1UtwtK6TxPZ8VubJ4UHie0RjD13QY4PENXqqEeMf3kAGiAhBQnwdsGGEeIj/POyihGzdiZnbAy5C+1WqWau8Wz4v/lc/IKD3Lmqap8GQvviFfmd+m6iWFs68nUVffy4svLE+5aB3xqA++Zs+hwkdfXtfwka9...
[ "assert math.isclose(\n production_cost(\n {\"materialA\": 19, \"materialB\": 16, \"materialC\": 24},\n {\"materialA\": 1, \"materialB\": 5, \"materialC\": 9},\n [200, 400, 400, 0, 100],\n ),\n 346500,\n)", "assert math.isclose(\n production_cost(\n {\"materialA\": 30, \"ma...
def production_cost( raw_material_cost: dict[str, float], raw_material_usage: dict[str, float], daily_production: list[int] ) -> float:
[ "list", "dictionary", "loop" ]
from code import production_cost import math
lbpp/python/159
python
url_search_param_value
Write a python function `manage_url_search_param_value(url_query: str, value: str, to_delete: bool) -> str` that accepts a url query string, a value, and a `to_delete` boolean. If no to_delete is provided it should add the value under the key called "value". If it is provided then it should delete any key with that val...
def manage_url_search_param_value(url_query: str, value: str, to_delete: bool) -> str: if to_delete: s = url_query.split("&") for i in range(len(s) - 1, -1, -1): k, v = s[i].split("=") if v == value: del s[i] return "&".join(s) else: return...
eJxrYJnKzsQABhEMQIZSWlF+rkJyfkqqQmZuQX5RiUJuYl5iemp8aVFOfHFqYlFyRnxBYlFibnxZYk5pakxeTJ6yQohrcEhMXmJxcSoh9RoxSom2hmpJtkZqybbGMUo6CjFKRiDKLTGnOFVTwdZWAUWFGliXLVAJzJ54Vz8XSuxUS7E1QrI3pKgU2Vqwo6hvlSE+LwJVQb1pSBW7jaGmmuD2JooiZCuVpugBALkFo5M=
[ "assert manage_url_search_param_value(\"a=1&b=2&c=3\", \"2\", False) == \"a=1&b=2&c=3&value=2\"", "assert manage_url_search_param_value(\"a=1&b=2&c=3&d=2\", \"2\", True) == \"a=1&c=3\"", "assert manage_url_search_param_value(\"a=1&b=2&c=3&d=2\", \"1\", False) == \"a=1&b=2&c=3&d=2&value=1\"", "assert manage_ur...
def manage_url_search_param_value(url_query: str, value: str, to_delete: bool) -> str:
[ "string" ]
from code import manage_url_search_param_value
lbpp/python/160
python
validate_spiral
Write a Python function named validate_spiral that checks whether a given 2D array with dimensions N x M (where N and M are the number of rows and columns, respectively) is a valid spiral. - The spiral should start in the top-left corner and spiral clockwise towards the center. - Each element in the spiral must be in ...
def validate_spiral(matrix: list[list[int]]) -> bool: """ Validates whether a given 2D array (N x M matrix) is a valid spiral. A valid spiral starts in the top-left corner and spirals clockwise towards the center, with each element in ascending order, incrementing by 1 each time, starting with 1. ...
eJytkk1OwzAQhZHgIKN2QyULxW7Tnz3dsmkXSI1VWcmALCV2lATKkkPATdhxOWacRKhlgVLwInEm9vf8PO/16v3z8iKM+w+ajB4qX0DqMwRblL5q4NnkNjMN7uvSViZPXOLGsF1vtokzdY0/V1zvdlKAEjDVAnZLASsBM54uBMwFxFpPesR+fXc7BNiBJM0lfcgZ47hA/yWxZUwSoRAFWRJf/C7n/CAPQUNPAMYwB+MyiMFUCPXBlCVmf7VGBw9uVGetc9Fq/q+RqG0GG4nA1mE7vpSYNpiBdWBaGPSNP9vYt87GusccofKH4Tg+teJH...
[ "assert validate_spiral([[1, 2, 3], [8, 9, 4], [7, 6, 5]])", "assert validate_spiral([[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]])", "assert not validate_spiral([[1, 2, 3], [8, 9, 4], [7, 5, 6]]) # 6 and 5 are swapped", "assert validate_spiral([[1, 2, 3, 4], [10, 11, 12, 5], [9, 8, 7, 6]])...
def validate_spiral(matrix: list[list[int]]) -> bool:
[ "array", "matrix" ]
from code import validate_spiral
lbpp/python/161
python
word_ranges
You are given a list of words each of k length and a list of character ranges of k length. The character ranges are expressed as [a-c], [m-o], etc. Each range represents a set of valid characters at that index. Return the subset of words from the list of words that are valid. For example, if you are given a list of wor...
# define a n-ary tree class to store the words class Trie: def __init__(self): self.children = {} self.is_end = False def insert(self, word: str): node = self for char in word: if char not in node.children: node.children[char] = Trie() nod...
eJzdUj0KwjAUduhBQlwUjDdws6uLDoIRSdvXH2mTmAQcRPAQehk3b2bbpNAi1E2KWd7Hy8v3Q97Ne7y8UX22zxLgWIkChSIClBVSKIPOQkUHxXgClFM+Rht/vaGcaQ2dy8mOYiZlDhTPEMUB44xbGKaglIURM6AthDwC142zRLtuopgsGfYzVNGR0HZTIh0rOZWA4iPRdQ2JKYenaLFAl46807w2hg/+avlr82lj3ljAes27x/XgR46W0KAjQVX/K1JMVCtSIzRoy9Cx3PsLg8oRENGzTV/2Bt/nbyHpdqM=
[ "assert word_range([\"apple\", \"banan\", \"cherr\", \"dates\", \"elder\", \"figss\", \"grape\"], [\"a-c\", \"h-p\", \"b-q\",\"j-s\",\"c-t\"]) == {\"apple\", \"cherr\"}", "assert word_range([\"apple\", \"banan\", \"cherr\", \"dates\", \"elder\", \"figss\", \"grape\"], [\"a-h\", \"h-t\", \"a-q\",\"j-s\",\"c-t\"]) ...
def word_range(words: list[str], ranges: list[str]) -> set[str]:
[ "tree", "traversal" ]
from code import word_range