task_id
stringlengths
12
14
prompt
stringlengths
273
1.94k
entry_point
stringlengths
3
31
canonical_solution
stringlengths
0
2.7k
test
stringlengths
160
1.83k
PythonSaga/100
from typing import List, Tuple, Dict, Any, Callable, Optional def input_func(user: str, house_value: int, income: int, vehicle_value: int) -> dict: """Create a class named tax, with following functions: 1. LandTax: calculate the land tax of a house i.e 2% of the house value 2. IncomeTax: calculate the in...
input_func
class Tax: def __init__(self, user): self.user = user def LandTax(self, house_value): return {'house tax': house_value * 0.02} def IncomeTax(self, income): return {'income tax': income * 0.1} def VehicleTax(self, vehicle_value): return {'vehicle tax': vehicle_value * 0...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("Alice", 300000, 80000, 75000) == {'house tax': 6000, 'income tax': 8000, 'vehicle tax': 3750} assert candidate("Bob", 450000, 120000, 60000) == {'house tax': 9000, 'income tax': 12000, 'vehicle tax': 3000} ass...
PythonSaga/101
from typing import List, Tuple, Dict, Any, Callable, Optional def input_func2(eqn: str) -> str: """I want to check whether the equation given by user is balanced or not in form of paranthesis and operators. Make a class named check_balance and conduct the test. There are four operators: +, -, *, / T...
input_func2
class CheckBalance: def __init__(self, eqn: str): self.eqn = eqn self.stack = [] self.pairs = {')': '(', '}': '{', ']': '['} def is_balanced(self) -> str: last = '' # Keep track of the last character processed for char in self.eqn: if char in '({[': ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("(a+b)*c") == "Balanced" assert candidate("(a+b)*c)") == "Not Balanced" assert candidate("(a+b)c") == "Not Balanced" assert candidate("(a+b)*[c-d]/{e+f}") == "Balanced"
PythonSaga/102
from typing import List, Tuple, Dict, Any, Callable, Optional def input_func3(lst1: List[int], lst2: List[int]) -> Tuple[List[int], str]: """Write a Python program that overloads the operator + and > for a Orders class. Take input from the user for the 2 orders in form of list and print the merged...
input_func3
class Orders: def __init__(self, order_list: List[int]): self.order_list = order_list def __add__(self, other): merged_list = self.order_list + other.order_list return Orders(merged_list) def __gt__(self, other): total_amount_self = sum(self.order_list) total_amount...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([1, 2, 3, 4, 5, 6], [10, 20, 30]) == ([1, 2, 3, 4, 5, 6, 10, 20, 30], "Order 2 > Order 1") assert candidate([5, 10, 15], [2, 7, 12]) == ([5, 10, 15, 2, 7, 12], "Order 1 > Order 2") assert candidate([1, 2, 3], [4...
PythonSaga/103
from typing import List, Tuple, Dict, Any, Callable, Optional def input_func4(animal: str) -> str: """I want to teach my nephew about sound and type of different animals Create one class animal which displays name of animal input by user. Create 4 classes: 1. Dog, type of animal: mammal, sound: bark...
input_func4
class Animal: def __init__(self, name: str, animal_type: str, sound: str): self.name = name self.animal_type = animal_type self.sound = sound def display_info(self) -> str: return f"Name of animal is {self.name}, it belongs to {self.animal_type} family and it {self.sound}." cla...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("dog") == "Name of animal is dog, it belongs to mammal family and it barks." assert candidate("cat") == "Name of animal is cat, it belongs to mammal family and it meows." assert candidate("duck") == "Name of ani...
PythonSaga/104
from typing import List, Tuple, Dict, Any, Callable, Optional def input_func5(dir: List[List[str, int]]) -> int: """I want to know how far I'm from origin if I move certain distance in certain direction Direction can be N,S,E,W and distance can be any positive integer Create class Distance that returns t...
input_func5
class Distance: def __init__(self): self.x = 0 # East-West position self.y = 0 # North-South position def update_position(self, distance: int, direction: str): if direction == 'N': self.y += distance elif direction == 'S': self.y -= distance eli...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([['N', 5], ['E', 3], ['S', 5], ['stop']]) == 3 assert candidate([['N', 5], ['N', 7], ['S', 5], ['stop']]) == 7 assert candidate([['E', 10], ['W', 5], ['N', 3], ['S', 3], ['stop']]) == 5 assert candidate([['E...
PythonSaga/105
from typing import List def mirror_matrix(n: int, matrix: List[List[int]]) -> List[List[int]]: """User wants to give a 2-D array of order N x N, print a matrix that is the mirror of the given tree across the diagonal. We need to print the result in such a way that swaps the values of the triangle above the d...
mirror_matrix
for i in range(n): for j in range(i + 1, n): # Swap the values across the diagonal matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] return matrix
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(3, [[1, 2, 4], [5, 9, 0], [3, 1, 7]]) == [[1, 5, 3], [2, 9, 1], [4, 0, 7]] assert candidate(2, [[1, 2], [3, 4]]) == [[1, 3], [2, 4]] assert candidate(4, [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15,...
PythonSaga/106
from typing import List def equivalent_matrices(n: int, m: int, matrix1: List[List[int]], matrix2: List[List[int]]) -> int: """User wants to give two 2-D array of order N x M, print the number of changes required to make M1 equal to M2. A change is as: 1. Select any one matrix out of two matrices. ...
equivalent_matrices
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(2, 2, [[1, 1], [1, 1]], [[1, 2], [3, 4]]) == 3 assert candidate(2, 2, [[1, 1], [1, 1]], [[1, 0], [0, -1]]) == -1 assert candidate(2, 3, [[1, 1, 1], [2, 2, 2]], [[2, 2, 2], [3, 3, 3]]) == 2 assert candidate(2...
PythonSaga/107
from typing import List def max_prize(n: int, m: int, matrix: List[List[int]]) -> int: """User wants to give a 2-D array of order N x M, print the maximum prize I can get by selecting any submatrix of any size. Take the value of n and m from the user and take n rows of input from the user and Print the maxim...
max_prize
def kadane(arr: List[int]) -> int: max_ending_here = max_so_far = arr[0] for x in arr[1:]: max_ending_here = max(x, max_ending_here + x) max_so_far = max(max_so_far, max_ending_here) return max_so_far def max_prize(n: int, m: int, matrix: List[List[int]]) -> int: maxSum = float('-inf') ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(4, 5, [[1, 2, -1, -4, -20], [-8, -3, 4, 2, 1], [3, 8, 10, 1, 3], [-4, -1, 1, 7, -6]]) == 29 assert candidate(3, 3, [[-1, 2, -3], [4, -5, 6], [-7, 8, -9]]) == 5 assert candidate(2, 2, [[1, -2], [3, 4]]) == 7 ...
PythonSaga/108
from typing import List def longest_path(n: int, m: int, matrix: List[List[int]]) -> int: """User wants to give a 2-D array of order N x M, print the maximum number of cells that you can visit in the matrix by starting from some cell. Take the value of n and m from the user and take n rows of input from the ...
longest_path
def dfs(i, j, n, m, matrix, dp): # If dp[i][j] is already computed, return its value if dp[i][j] != 0: return dp[i][j] # Possible moves: up, down, left, right directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] max_path = 1 # Minimum path length starting from cell (i, j) is 1 for ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(2, 3, [[3, 1, 6], [-9, 5, 7]]) == 4 assert candidate(2, 2, [[4, 2], [4, 5]]) == 2 assert candidate(3, 3, [[1, 2, 3], [6, 5, 4], [7, 8, 9]]) == 9 assert candidate(2, 2, [[-1, 6], [5, 3]]) == 2
PythonSaga/109
from typing import List def max_prod(n: int, m: int, matrix: List[List[int]]) -> int: """You are given an m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0,...
max_prod
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(3, 3, [[1, -2, -3], [-2, -3, -3], [-3, -3, -2]]) == -1 assert candidate(2, 2, [[1, 2], [0, -4]]) == 0 assert candidate(2, 3, [[1, 2, 3], [4, 5, -6]]) == -1 assert candidate(3, 3, [[1, 1, 1], [1, -1, -2], [-1...
PythonSaga/110
from typing import List def binary_tree(arr: List[int]) -> bool: """My uncle gave me a Binary Tree. He asked me to Check whether all of its nodes have the value equal to the sum of their child nodes. If yes, return True. Otherwise, return False. Take input from the user and print the result. E...
binary_tree
def is_sum_tree(arr, index=0): # Base case: if the current node is a leaf or beyond the length of the array, it's considered a sum tree if index >= len(arr) or 2 * index + 1 >= len(arr): return True # Calculate the index of left and right children left = 2 * index + 1 right = 2 * index + 2 ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([10, 10]) == True assert candidate([1, 4, 3, 5]) == False assert candidate([1, 2, 3, 6, 3, 2, 1]) == False assert candidate([12, 9, 3, 6, 3, 2, 1]) == True assert candidate([]) == True
PythonSaga/111
from typing import List def floor_ceil(num: int, arr: List[int]) -> List[int]: """My teacher gave me a binary search tree, and I have to make a function to find the floor and ceil of a number in the tree. Take a binary search tree and a number as input from the user and return the floor and ceil of the number...
floor_ceil
def find_floor_ceil(arr, num, index=0, floor=None, ceil=None): # Base case: if the current index is out of range or the node is None if index >= len(arr) or arr[index] is None: return floor, ceil # If the current node's value is equal to num, both floor and ceil are the num itself if arr[index]...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(10,[10, 10]) == [10,10] assert candidate(2,[1, 4, 3, 5]) == [1,3] assert candidate(3,[8, 5, 9, 2, 6, None, 10]) == [2,5] assert candidate(1,[8, 5, 9, 2, 6, None, 10]) == [None,2]
PythonSaga/112
from typing import List def merge_bst(arr1: List[int], arr2: List[int]) -> List[int]: """I have 2 binary search trees, and I want to merge them into one binary search tree. Take 2 binary search trees as input from the user, and return an inorder traversal of the binary search tree as output. Example: ...
merge_bst
def inorder_from_level_order(arr, index=0, inorder=[]): if index >= len(arr) or arr[index] is None: return # Traverse left subtree inorder_from_level_order(arr, 2 * index + 1, inorder) # Visit node inorder.append(arr[index]) # Traverse right subtree inorder_from_level_order(arr, 2 * ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_data1 = [3, 1, 5] input_data2 = [4, 2, 6] assert candidate(input_data1, input_data2) == [1, 2, 3, 4, 5, 6] # Test Case 2: input_data3 = [8, 2, 10, 1] input_data4 = [5, 3, None, 0] assert...
PythonSaga/113
from typing import List def valid_bst(arr: List[int]) -> bool: """A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtre...
valid_bst
class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def insert_bst(root, value): if not root: return TreeNode(value) if value < root.value: root.left = insert_bst(root.left, value) elif value > root.value: roo...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): input_data1 = [2, 1, 3] assert candidate(input_data1) == True input_data2 = [5, 1, 4, None, None, 3, 6] assert candidate(input_data2) == False input_data3 = [5, 1, 6, None, None, 5.5, 7] assert candidate(input_data3...
PythonSaga/114
from typing import List def longest_univalue_path(arr: List[int]) -> int: """I have the root of a binary tree, and task is to return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root. The length of the path between two nodes is...
longest_univalue_path
def longest_univalue_path(arr: List[int]) -> int: def dfs(index, value): if index >= len(arr) or arr[index] is None: return 0 left_len = dfs(2 * index + 1, arr[index]) right_len = dfs(2 * index + 2, arr[index]) # Update global maximum using paths from left and right child...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([5, 4, 5, 1, 1, 5, 5]) == 2 assert candidate([2, 4, 5, 4, 4, 5]) == 2 assert candidate([1, 1, 1, 1, 1, None, 1]) == 4 assert candidate([1, 2, 2, 2, 2, 3, 3, 2]) == 3
PythonSaga/115
from typing import List def max_heapify(arr: List[int]) -> List[int]: """My friend gave me binary tree and asked me to construct max heap from it and return level order traversal of max heap. Take binary tree as input from user and construct max heap from it and return level order traversal of heap. Examp...
max_heapify
def heapify(arr: List[int], n: int, i: int): largest = i # Initialize largest as root left = 2 * i + 1 # left = 2*i + 1 right = 2 * i + 2 # right = 2*i + 2 # If left child is larger than root if left < n and arr[largest] < arr[left]: largest = left # If right child is larger than la...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): input_data1 = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17] assert candidate(input_data1) == [17, 15, 13, 9, 6, 5, 10, 4, 8, 3, 1] input_data2 = [10, 5, 7, 2, 1, 8, 3, 6, 9, 4] assert candidate(input_data2) == [10, 9, 8, 6, 4, 7, 3...
PythonSaga/116
from typing import List def lenght_of_rope(n:int, arr: List[int]) -> int: """There are given N ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to sum of their lengths. The task is to connect the ropes with minimum cost. Take number of...
lenght_of_rope
# Initialize min heap with rope lengths heapq.heapify(arr) total_cost = 0 # Initialize total cost # Keep connecting ropes until only one is left while len(arr) > 1: # Extract the two smallest ropes first = heapq.heappop(arr) second = heapq.heappop(arr) # Connect them connected_rope = first + sec...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_data1 = 4, [5, 4, 3, 7] assert candidate(*input_data1) == 38 # Test Case 2: input_data2 = 3, [1, 2, 3] assert candidate(*input_data2) == 9 # Test Case 3: input_data3 = 5, [10, 2, 8, 5,...
PythonSaga/117
def rearrange(s: str) -> bool: """I have a word/string which has repeated characters. I want to rearrange the word such that no two same characters are adjacent to each other. If no such arrangement is possible, then return False, else return true. Take string as input from user. Use heap conce...
rearrange
char_freq = {} # Count the frequency of each character in the string for char in s: char_freq[char] = char_freq.get(char, 0) + 1 # Create a max heap based on negative frequencies max_heap = [(-freq, char) for char, freq in char_freq.items()] heapq.heapify(max_heap) result = [] while len(max_heap) > 1: # Ext...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_data1 = 'aaabc' assert candidate(input_data1) == True # Test Case 2: input_data2 = 'aa' assert candidate(input_data2) == False # Test Case 3: input_data3 = 'aabbccc' assert candida...
PythonSaga/118
from typing import Dict def huff_encode(n:int, d:Dict) -> Dict: """I need to implement huffman coding for input characters based on their frequency. Take input for characters and their frequency from user. and then encode them using huffman coding. Example: Input: 6, {'a': 5, 'b': 9, 'c': 12, 'd': 13...
huff_encode
class Node: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def build_huffman_tree(freq_dict): min_heap = [Node(char, freq) for char, freq in freq_dict.items(...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_data1 = 6, {'a': 5, 'b': 9, 'c': 12, 'd': 13, 'e': 16, 'f': 45} assert candidate(*input_data1) == {'f': '0', 'c': '100', 'd': '101', 'a': '1100', 'b': '1101', 'e': '111'} # Test Case 2: input_data2...
PythonSaga/119
from typing import List def merge_lists(n:int, lists:List[List[int]]) -> List[int]: """Take k sorted lists of size N and merge them into one sorted list. You can use a heap to solve this problem. Take input from the user for the number of lists and the elements of the lists. Example: Input: 3, [[1, 3...
merge_lists
result = [] min_heap = [] # Initialize the heap with the first element from each list along with the list index for i, lst in enumerate(lists): if lst: heapq.heappush(min_heap, (lst[0], i, 0)) while min_heap: val, list_index, index_in_list = heapq.heappop(min_heap) result.append(val) # Move t...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_data1 = 3, [[1, 3, 5, 7], [2, 4, 6, 8], [0, 9, 10, 11]] assert candidate(*input_data1) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # Test Case 2: input_data2 = 2, [[-1, 0, 2, 4], [3, 5, 6, 8]] as...
PythonSaga/120
from typing import List def autoComplete(words: List[str], word: str) -> List[str]: """I came to know that auto complete feature while typing is performed using Trie data structure. Do a task where take a input of multiple words from user and a word to be completed. Return all the words that can be completed ...
autoComplete
class TrieNode: def __init__(self): self.children = {} self.is_end_of_word = False def insert_word(root, word): node = root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.is_end_of_word = True ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_words1 = ['hello', 'hell', 'hi', 'how', 'are', 'you', 'hero', 'hey'] input_word1 = 'he' assert candidate(input_words1, input_word1) == ['hello', 'hell', 'hero', 'hey'] # Test Case 2: input_word...
PythonSaga/121
from typing import List def rename_cities(cities: List[str]) -> List[str]: """Some cities are going to be renamed and accordingly name of their railway stations will also change. Changing the name of railway station should also result in changed station code. Railways have an idea that station code shou...
rename_cities
city_count = {} # Tracks the count of each city used_codes = set() # Tracks all used codes to ensure uniqueness codes = [] # Stores the resulting station codes for city in cities: # Increment the city count or initialize it city_count[city] = city_count.get(city, 0) + 1 if city_count[city] == 1: ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_cities1 = ['Delhi', 'Mumbai', 'Chennai', 'Kolkata', 'Dehradun', 'Delhi'] assert candidate(input_cities1) == ['D', 'M', 'C', 'K', 'Deh', 'Delhi2'] # Test Case 2: input_cities2 = ['Shimla', 'Safari',...
PythonSaga/122
from typing import List def max_xor(nums: List[int]) -> int: """Given the sequence of number in a list. choose the subsequence of number in the list such that Bitwise Xor of all the elements in the subsequence is maximum possible. Try to use trie data structure to solve this problem. Take list as inp...
max_xor
class TrieNode: def __init__(self): self.children = {} def insert(num, root): node = root for i in range(31, -1, -1): bit = (num >> i) & 1 if bit not in node.children: node.children[bit] = TrieNode() node = node.children[bit] def find_max_xor(nums, root): ma...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_nums1 = [8, 1, 2, 12] assert candidate(input_nums1) == 14 # Test Case 2: input_nums2 = [1, 2, 3, 4] assert candidate(input_nums2) == 7 # Test Case 3: input_nums3 = [5, 10, 15, 20, 25] ...
PythonSaga/123
from typing import List def pal_pairs(words: List[str]) -> List[List[str]]: """Given a list of words, return a list of all possible palindrome pairs. A palindrome pair is a pair of words that when concatenated, the result is a palindrome. Take a list of words as input from user and return a list of palindro...
pal_pairs
def is_palindrome(word): return word == word[::-1] def pal_pairs(words: List[str]) -> List[List[str]]: result = [] word_set = set(words) for i in range(len(words)): for j in range(len(words)): if i != j: concat_word = words[i] + words[j] if is_palind...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_words1 = ['code', 'edoc', 'da', 'd'] assert candidate(input_words1) == [['code', 'edoc'], ['da', 'd']] # Test Case 2: input_words2 = ['abcd', 'dcba', 'lls', 's', 'sssll'] assert candidate(input...
PythonSaga/124
from typing import List def cross_words(n:int, m:int, board: List[List[str]], words: List[str]) -> List[str]: """Given an m x n board of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are hor...
cross_words
def is_valid(board, visited, row, col): return 0 <= row < len(board) and 0 <= col < len(board[0]) and not visited[row][col] def dfs(board, visited, row, col, current_word, trie, result): if '#' in trie: result.append(current_word) trie['#'] = None # Mark the word as found in the trie dire...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_board1 = [['o','a','a','n'],['e','t','a','e'],['i','h','k','r'],['i','f','l','v']] input_words1 = ['oath', 'pea', 'eat', 'rain'] assert candidate(4, 4, input_board1, input_words1) == ['oath', 'eat'] ...
PythonSaga/125
from typing import List def max_profit(n:int, items: List[List[int]], capacity: int) -> int: """Given a list of items and a capacity, return the maximum value of the transferred items. Each item is a list of [value, weight]. The item can be broken into fractions to maximize the value of the transferred item...
max_profit
# Calculate value per unit weight for each item and store it along with the item items_with_ratio = [(item[0] / item[1], item[0], item[1]) for item in items] # (value/weight, value, weight) # Sort the items by value per unit weight in descending order items_with_ratio.sort(reverse=True) max_value = 0 # Maximum valu...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_items1 = [[60, 10], [100, 20], [120, 30]] input_capacity1 = 50 assert candidate(3, input_items1, input_capacity1) == 240 # Test Case 2: input_items2 = [[60, -10], [100, 20]] input_capacity2...
PythonSaga/126
from typing import List def max_prof(n: int, jobs: List[List[int]]) -> List[int]: """I want to sequence the job in such a way that my profit is maximized by the end of time. let say i'm given N jobs with their deadline and profit. I need to find the sequence of jobs that will maximize my profit. Each...
max_prof
# Sort jobs by profit in descending order jobs.sort(key=lambda x: x[1], reverse=True) # Initialize variables max_deadline = max(job[0] for job in jobs) # Find the maximum deadline slots = [False] * max_deadline # To keep track of occupied time slots job_count = 0 # To count the number of jobs done total_profit = 0 ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): # Test Case 1: input_jobs1 = [[4, 20], [1, 10], [1, 40], [1, 30]] assert candidate(4, input_jobs1) == [60, 2] # Test Case 2: input_jobs2 = [[2, 30], [3, 40], [4, 50], [5, 60]] assert candidate(4, input_jobs2) == [1...
PythonSaga/127
from typing import List def min_cost(length: int, width: int, cost: List[List[int]]) -> int: """I have a big piece of granite tile that I want to cut into squares. Size of my tile is length 'p' and width 'q'. I want to cut it into p*q squaressquares such that cost of breaking is minimum. cutting cost fo...
min_cost
# Separate the horizontal and vertical costs horizontal_cuts = cost[0] vertical_cuts = cost[1] # Add a marker to distinguish between horizontal and vertical cuts horizontal_cuts = [(c, 'h') for c in horizontal_cuts] vertical_cuts = [(c, 'v') for c in vertical_cuts] # Combine and sort all cuts by cost in descending or...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): length1, width1 = 6, 4 cost1 = [[2, 1, 3, 1, 4], [4, 1, 2]] assert candidate(length1, width1, cost1) == 42 length3, width3 = 4, 4 cost3 = [[1, 1, 1], [1, 1, 1]] assert candidate(length3, width3, cost3) == 15
PythonSaga/128
from typing import List def equal_ele(nums: List[int], k: int) -> int: """User provides list of number and value X. We have to find the maximum number of equal elements possible for the list just by increasing the elements of the list by incrementing a total of atmost k. Take input from user for li...
equal_ele
nums.sort() # Step 1: Sort the list max_equal = 1 # To keep track of the maximum number of equal elements j = 0 # Start of the sliding window for i in range(len(nums)): # Step 3: Calculate the total increments needed for the current window while nums[i] * (i - j + 1) - sum(nums[j:i + 1]) > k: j += 1...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): # Test Case 1: nums1, k1 = [5, 5, 3, 1], 5 assert candidate(nums1, k1) == 3 # Test Case 2: nums2, k2 = [2, 4, 9], 3 assert candidate(nums2, k2) == 2 # Test Case 3: nums3, k3 = [1, 2, 3, 4, 5], 3 assert candidate(...
PythonSaga/129
def max_palindrom(num: str) -> str: """My friend say there's always some possibliy to make any given number into palindrome by permutation of its digits. So take a input from user for a number and return a maximum possible palindrome number from it. and if not possible return 'not possible'. Example: ...
max_palindrom
# Count the frequency of each digit digit_count = [0] * 10 for digit in num: digit_count[int(digit)] += 1 # Build the left half of the palindrome left_half = [] middle_digit = "" for digit in range(9, -1, -1): count = digit_count[digit] if count % 2 != 0: if middle_digit: return "not p...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): # Test Case 1: num1 = '313515' assert candidate(num1) == '531135' # Test Case 2: num2 = '123' assert candidate(num2) == 'not possible' # Test Case 3: num3 = '1223333' assert candidate(num3) == '3321233' # Te...
PythonSaga/130
from typing import List def path(n: int, maze: List[List[int]]) -> List[List[int]]: """I came to know about a very interesting topic known as backtracking. So, my friend gave me a problem to solve using backtracking. Let's say I have a maze and I have to find the path from source to destination. Ma...
path
def solve_maze(maze, x, y, solution, n): # Base Case: If x, y is the destination, return True if x == n - 1 and y == n - 1 and maze[x][y] == 1: solution[x][y] = 1 return True # Check if maze[x][y] is a valid move if 0 <= x < n and 0 <= y < n and maze[x][y] == 1: # Mark x, y ...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): n1 = 4 maze1 = [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 1], [1, 1, 1, 1]] assert candidate(n1, maze1) == [[1, 0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 1]] n2 = 3 maze2 = [[1, 0, 0], [1, 1, 1], [0, 0, 1]] assert candidate(...
PythonSaga/131
def big_number(num: str, swaps: int) -> str: """In a lottery game, I have a large number and value X. I'm asked to swap the digits of the number at most X times such that the value of the number is maximized. I have to print the maximum value of the number after swapping the digits at most X times. Take ...
big_number
# Convert the string to a list of digits for easier manipulation num_list = list(num) i = 0 while swaps > 0 and i < len(num_list) - 1: max_digit_index = i # Find the maximum digit in the remaining part of the number for j in range(i + 1, len(num_list)): if num_list[j] > num_list[max_digit_index]: ...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate('1234567', 4) == '7654321' assert candidate('3435335', 3) == '5543333' assert candidate('987654321', 5) == '987654321' assert candidate('102233', 2) == '332210'
PythonSaga/132
from typing import List def graph_colooring(n: int, m: int, e: int, edges: List[List[int]]) -> bool: """I'm assigned an undirected graph and an integer M. The task is to determine if the graph can be colored with at most M colors such that no two adjacent vertices of the graph are colored with the same color...
graph_colooring
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(4, 3, 5, [[0, 1], [1, 2], [1, 3], [2, 3], [3, 0], [0, 2]]) == 1 assert candidate(3, 2, 3, [[0, 1], [1, 2], [2, 0]]) == 0 assert candidate(5, 3, 7, [[0, 1], [0, 2], [1, 2], [1, 3], [2, 4], [3, 4], [4, 0]]) == 1 assert ...
PythonSaga/133
def additive_number(num: str) -> str: """By tossing a number at me, my teacher asked to tell whether it is additive or not. An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each s...
additive_number
def additive_number(num: str) -> str: def is_additive(s, num1, num2): while s: num_sum = str(int(num1) + int(num2)) if not s.startswith(num_sum): return False s = s[len(num_sum):] num1, num2 = num2, num_sum return True n = len(num)...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate('112358') == 'It is an additive number' assert candidate('199100199') == 'It is an additive number' assert candidate('123456') == 'It is not an additive number' assert candidate('111222333') == 'It is an additive numb...
PythonSaga/134
from typing import List def solve_eq(left: List[str], right: str) -> bool: """I have an equation, represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: 1. Each character is decoded as one digit (0 - 9). 2. No ...
solve_eq
unique_chars = set(''.join(left) + right) # Gather all unique characters if len(unique_chars) > 10: # More unique characters than digits return False char_to_digit = {} digits_taken = set() def solve(index): if index == len(unique_chars): # All characters have been assigned digits left_sum = sum(in...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(['send', 'more'], 'money') == True assert candidate(['ox', 'ox'], 'xx') == False assert candidate(['bat', 'tab'], 'bat') == False assert candidate(['house', 'water'], 'money') == False
PythonSaga/135
def is_good(s: str) -> str: """I have a task to find whether a string is good or not. A string s is good if for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. Take input from the user and print whether the string is good or not. return the longest substring ...
is_good
def is_good(s: str) -> str: def is_nice(substr): return all(c.islower() and c.upper() in substr or c.isupper() and c.lower() in substr for c in set(substr)) n = len(s) longest_nice_substr = "" for i in range(n): for j in range(i + 1, n + 1): substring = s[i:j] if...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate('uSaisAI') == 'SaisAI' assert candidate('xYz') == 'Not good' assert candidate('aAbBcC') == 'aAbBcC' assert candidate('AbCdEfG') == 'Not good'
PythonSaga/136
from typing import List def power_mod(a: int, b: List[int]) -> int: """I have a very large number a and another number b. b is such large it is given in form of list. I need to calculate pow(a,b) % 1337. But I have to use a divide and conquer approach. Take a and b as input from the user and return...
power_mod
def power_mod(a: int, b: List[int]) -> int: MOD = 1337 def pow_helper(base, exponent): if exponent == 0: return 1 if exponent == 1: return base % MOD half_pow = pow_helper(base, exponent // 2) result = (half_pow * half_pow) % MOD if exponent % 2...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(2, [3]) == 8 assert candidate(2, [1, 0]) == 1024 assert candidate(3, [2, 5]) == 1151 assert candidate(5, [1, 3, 7]) == 52
PythonSaga/137
from typing import List def max_sum(arr: List[int]) -> int: """I have a list of integers. I want to find the maximum sum of a sublist. You can access the list in circular fashion. Take input from the user and print the maximum sum and the sublist. Example: Input: [1, -5, 6, -2] Output: 6 ...
max_sum
def kadane(arr: List[int]) -> int: """Standard Kadane's algorithm to find the maximum subarray sum.""" max_ending_here = max_so_far = arr[0] for x in arr[1:]: max_ending_here = max(x, max_ending_here + x) max_so_far = max(max_so_far, max_ending_here) return max_so_far def max_sum(arr: L...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([1, -5, 6, -2]) == 6 assert candidate([9, -4, 9]) == 18 assert candidate([5, -3, 5]) == 10 assert candidate([4, -1, 2, -1]) == 5 assert candidate([-2, 8, -3, 7, -1]) == 12
PythonSaga/138
from typing import List def recover_list(n: int, sums: List[int]) -> List[int]: """My job is to recover all the forgotten list by subset sums. given a list sums containing the values of all 2^n subset sums of the unknown array (in no particular order). Take input from the user for the length of the forgo...
recover_list
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(3, [-3, -2, -1, 0, 0, 1, 2, 3]) == [1, 2, -3] assert candidate(2, [0, 0, 0, 0]) == [0, 0] assert candidate(2, [-1, 0, -1, 0]) == [0, -1]
PythonSaga/139
from typing import List def being_sum(being: List[int], lower: int, upper: int) -> int: """I have a list 'being' of integers and I want to find the being-sum. Given two integers lower and upper, return the number of being-sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum ...
being_sum
def being_sum(being: List[int], lower: int, upper: int) -> int: n = len(being) prefix_sums = [0] * (n + 1) # Initialize prefix sums array with an extra 0 at the beginning # Compute prefix sums for i in range(n): prefix_sums[i + 1] = prefix_sums[i] + being[i] count = 0 # Iterate throug...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([-2, 5, -1], -2, 2) == 3 assert candidate([1, 2, 3], 0, 5) == 5 assert candidate([3, 2, 1, 5], 1, 6) == 8
PythonSaga/140
def nCr(n: int, r: int) -> int: """I'm very much interested in mathematical problems, and today I learned nCr. Help me to implement it using dynamic programming. Take input from the user n and r and return nCr. Example: Input: 4, 2 # here 4 is n and 2 is r Output: 6 Input: 3, 2 Outpu...
nCr
def nCr(n: int, r: int) -> int: # Using dynamic programming to calculate binomial coefficient dp = [[0] * (r + 1) for _ in range(n + 1)] for i in range(n + 1): for j in range(min(i, r) + 1): if j == 0 or j == i: dp[i][j] = 1 else: dp[i][j] = d...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(4, 2) == 6 assert candidate(3, 2) == 3 assert candidate(6, 3) == 20 assert candidate(8, 4) == 70
PythonSaga/141
def bouncing_balls(n: int, h: int) -> int: """I have to test my bouncing ball, but there's a catch. The ball only bounces if it falls from a certain height; otherwise, it will burst if the height is above that. So provided N identical balls and a height H (1 to H), there exists a threshold T (1 to H) such...
bouncing_balls
ballFloor = [[0 for x in range(k + 1)] for x in range(n + 1)] for i in range(1, n + 1): ballFloor[i][1] = 1 ballFloor[i][0] = 0 for j in range(1, k + 1): ballFloor[1][j] = j for i in range(2, n + 1): for j in range(2, k + 1): ballFloor[i][j] = INT_MAX for x in range(1, j + 1): ...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(2, 10) == 4 assert candidate(1, 2) == 2 assert candidate(3, 15) == 5 assert candidate(5, 25) == 5
PythonSaga/142
def zebra_crossing(n: int) -> int: """I'm waiting for a bus, and now I'm getting bored. To entertain myself, I looked around and found a zebra crossing. There can be two ways to cross the road. If there are n white stripes on the zebra crossing, then I can cross either by stepping 1 stripe at a time or 2 ...
zebra_crossing
def zebra_crossing(n): def f(n, dp): if n == 0: return 1 if n == 1: return 1 if n == 2: return 2 if dp[n] != -1: return dp[n] one_step = f(n - 1, dp) two_step = f(n - 2, dp) dp[n] = one_step + two_step re...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(4) == 5 assert candidate(10) == 89 assert candidate(8) == 34 assert candidate(2) == 2
PythonSaga/143
def count_ways(number: str) -> int: """I wrote down a string of positive integers named 'number' but forgot to include commas to separate the numbers. The list of integers is non-decreasing, and no integer has leading zeros. I need to figure out the number of possible ways I could have written down the st...
count_ways
MOD = 10**9 + 7 def count_ways(number: str) -> int: n = len(number) dp = [0] * (n + 1) dp[0] = 1 # Base case for i in range(1, n + 1): for length in range(1, 4): # Check substrings of length 1 to 3 (since integers can range from 1 to 999) if i - length >= 0: subst...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate('327') == 2 assert candidate('094') == 0 assert candidate('111') == 2
PythonSaga/144
from typing import List def treasureHunt(a: int, b: int, x: int, forbidden: List[int]) -> int: """I'm playing a game on road where to win treasure I have to hop forward or backward on the x-axis. I start at position 0, and my treasure is at position x. There are rules for how I can hop: I can jump ...
treasureHunt
MOD = 10**9 + 7 # For large numbers visited = set() # To keep track of visited positions with a flag for last move forbidden = set(forbidden) # Convert list to set for efficient lookups queue = deque([(0, 0, False)]) # Position, steps, last move was backward while queue: position, steps, last_backward = queue....
def check(candidate): assert candidate(15, 13, 11, [8, 3, 16, 6, 12, 20]) == -1 assert candidate(16, 9, 7, [1, 6, 2, 14, 5, 17, 4]) == 2 assert candidate(3, 15, 9, [14,4,18,1,15]) == 3
PythonSaga/145
from collections import deque from typing import List def houses(n:int, connections:List[List[int]]) -> List[int]: """I'm standing at entry point of village. In this village there's no proper streets. Houses are randomly connected with each other, but there's always a way to reach all houses from starting poin...
houses
order = [] # To store the order of visiting houses visited = [False] * n # To keep track of visited houses queue = deque([0]) # Start from house 0 while queue: house = queue.popleft() if not visited[house]: order.append(house) visited[house] = True # Enqueue all connected, unvisited ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5, [[1, 2, 3], [], [4], [], []]) == [0, 1, 2, 3, 4] assert candidate(3, [[1, 2], [], []]) == [0, 1, 2] assert candidate(6, [[1, 2], [3, 5], [4], [], [], []]) == [0, 1, 2, 3, 5, 4] assert candidate(4, [[1, 2]...
PythonSaga/146
from collections import deque from typing import List def knight_moves(n:int, start:List[int], end:List[int]) -> int: """I started playing chess now a days. And now i have curiousity to how many steps it would take to reach from one position to another using knight. Let's say i have a chess board of N*N size...
knight_moves
from collections import deque source_row = KnightPos[0] - 1 source_col = KnightPos[1] - 1 dist = (TargetPos[0] - 1, TargetPos[1] - 1) queue = deque([(source_row, source_col, 0)]) deltas = [(2, 1), (1, 2), (-2, 1), (-1, 2), (2, -1), (1, -2), (-2, -1), (-1, -2)] visited = set() while queue: row, col, step = que...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(6, [4, 5], [1, 1]) == 3 assert candidate(8, [2, 2], [7, 7]) == 4 assert candidate(5, [0, 0], [4, 4]) == 4 assert candidate(4, [1, 1], [3, 3]) == 4
PythonSaga/147
from typing import List def remove_poles(v:int, w:int, wires:List[List[int]]) -> List[int]: """I have new job where i have to remove electric poles. There a v electric poles conected by w wires in random order. But soome how each pole is connected to every other pole directly or indirectly. let's say this comp...
remove_poles
def dfs(v, u, visited, disc, low, parent, ap, graph, time): children = 0 visited[u] = True disc[u] = low[u] = time[0] time[0] += 1 for neighbour in graph[u]: if not visited[neighbour]: parent[neighbour] = u children += 1 dfs(v, neighbour, visited, disc, l...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5, 5, [[0, 1], [1, 4], [4, 2], [2, 3], [3, 4]]) == [1, 4] assert candidate(5, 4, [[0, 1], [1, 4], [4, 2], [2, 3]]) == [1, 4, 2] assert candidate(5, 5, [[0, 1], [1, 2], [0, 2], [2, 3], [3, 4]]) == [2, 3]
PythonSaga/148
from typing import List def strongly_connected(S:int, T:int, tracks:List[List[int]]) -> List[List[int]]: """I'm the new railway state incharge and I want to know few things about railway networks. right now there are S stations and T tracks in between them . Some how all stations are connected to some other st...
strongly_connected
def dfs(graph, v, visited, stack): visited[v] = True for i in graph[v]: if not visited[i]: dfs(graph, i, visited, stack) stack.append(v) def transpose(graph, S): gT = [[] for _ in range(S)] for i in range(S): for j in graph[i]: gT[j].append(i) return gT ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5, 5, [[1,0],[0,2],[2,1],[0,3],[3,4]]) == [[0,1,2] ,[3] ,[4]] assert candidate(3, 3, [[0,1],[1,2],[2,0]]) == [[0,1,2]] assert candidate(9, 17, [[0,2],[0,1],[1,0],[1,3],[2,0],[2,3],[3,4],[4,3],[5,1],[5,4],[5,7],[...
PythonSaga/149
from typing import List def maze(n:int, m:int, maze:List[List[str]]) -> bool: """I'n new game of maze intead of moving from 0,0 to n,n you will be given start and end point any where in maze and you have to find whether you can reach from start to end or not. You can traverse up, down, right and left. The...
maze
def dfs(maze, i, j, visited): # Base conditions if not (0 <= i < len(maze) and 0 <= j < len(maze[0])) or maze[i][j] == '0' or visited[i][j]: return False if maze[i][j] == 'D': # Destination found return True # Mark the current cell as visited visited[i][j] = True # Explore...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5, 5, [['X', '0', 'X', '0', '0'], ['X', '0', '0', '0', 'X'], ['X', 'X', 'X', 'X', 'X'], ['0', 'D', 'X', '0', '0'], ...
PythonSaga/150
from typing import List def student_room(query: List[List[int]]) -> List[bool]: """I have to put few students in different rooms. At a time one student can be in one room. in one room there can be more than one student. If same student is added with another student, it goes to same room. Do two task : ...
student_room
def find(parent, i): if parent[i] != i: parent[i] = find(parent, parent[i]) # Path compression return parent[i] def union(parent, a, b): rootA = find(parent, a) rootB = find(parent, b) if rootA != rootB: parent[rootB] = rootA # Merge the sets def student_room(query: List[List[int...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([[1, 1, 3], [2, 1, 4], [1, 2, 3], [2, 1, 3], [3]]) == [False, True] assert candidate([[1, 1, 2], [1, 3, 4], [2, 1, 4], [2, 2, 3], [3]]) == [False, False] assert candidate([[1, 1, 2], [1, 3, 4], [2, 1, 4], [1, 2,...
PythonSaga/151
from typing import List def water_pipeline(tanks: int, pipes: List[List[int]]) -> bool: """I have a water pipeline system with water tanks and pipes. All pipes are biderctional and all tanks are connected to each other either directly or indirectly. There's no self loop in the system. I want to find all t...
water_pipeline
def find(parent, i): if parent[i] != i: parent[i] = find(parent, parent[i]) # Path compression return parent[i] def union(parent, a, b): rootA = find(parent, a) rootB = find(parent, b) if rootA == rootB: # A cycle is found return True parent[rootB] = rootA # Merge the sets ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(5, [[1, 3], [3, 0], [0, 2], [2, 4], [4, 0]]) == True assert candidate(4, [[0, 1], [1, 2], [2, 3], [3, 0]]) == True assert candidate(3, [[0, 1], [1, 2]]) == False assert candidate(6, [[0, 1], [1, 2], [2, 3], ...
PythonSaga/152
from typing import List def water_supply(villages: int, wells: List[int], pipes: List[List[int]]) -> int: """I have an N number of villages numbered 1 to N, an list wells[] where wells[i] denotes the cost to build a water well in the i'th city, a 2D array pipes in form of [X Y C] which denotes that the ...
water_supply
def find(parent, i): if parent[i] != i: parent[i] = find(parent, parent[i]) # Path compression return parent[i] def union(parent, rank, x, y): xroot = find(parent, x) yroot = find(parent, y) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(3, [1, 2, 2], [[1, 2, 1], [2, 3, 1]]) == 3 assert candidate(4, [2, 3, 1, 4], [[1, 2, 2], [2, 3, 3], [3, 4, 4]]) == 9 assert candidate(5, [1, 2, 3, 4, 5], [[1, 2, 1], [3, 4, 2], [4, 5, 3], [2, 3, 1]]) == 8 as...
PythonSaga/153
from typing import List def gang_fight(fights: List[List[int]]) -> int: """There's a fight going on in the school. It is between 2 gangs. Let's say there are N fights going on between gang A and gang B. We have 2D list of size N, Denotig that student list[i][0] and list[i][1] are fighting with each other...
gang_fight
def is_bipartite(graph, start, color): queue = deque([start]) color[start] = 1 # Assign a color to the starting vertex while queue: u = queue.popleft() for v in graph[u]: if color[v] == -1: # If not colored color[v] = 1 - color[u] # Assign an alternate color ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([[1, 2], [2, 3], [2, 4], [2, 5]]) == 4 assert candidate([[1, 2], [2, 3], [3, 1]]) == -1 assert candidate([[1, 2], [2, 3], [3, 4], [3, 5], [6, 7], [7, 8], [7, 9], [7, 10]]) == 7
PythonSaga/154
from typing import List def colony_pipes(houses: int, pipes: int, connections: List[List[int]]) -> List[int]: """i'm connecting houses in colony with pipeline. I have H houses and P pipes. I can conect one pipe between two houses (a to b). after each connection I have to print the minimmum differnce possi...
colony_pipes
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(2, 1, [[1, 2]]) == [0] assert candidate(4, 2, [[1, 2], [2, 4]]) == [0, 2] assert candidate(5, 3, [[1, 2], [3, 4], [4, 5]]) == [0, 0, 1] assert candidate(6, 4, [[1, 2], [3, 4], [2, 5], [6, 1]]) == [0, 0, 1, 2...
PythonSaga/155
from typing import List def water_plant(cities: int, connections: List[List[int]]) -> int: """i have a one water processong plant and a city. The job of water plant is to supply water to the city. But in between city there are other small villages. So the water plant has to supply water to first theses village...
water_plant
def bfs(rGraph, s, t, parent): visited = [False] * len(rGraph) queue = deque() queue.append(s) visited[s] = True while queue: u = queue.popleft() for ind, val in enumerate(rGraph[u]): if not visited[ind] and val > 0: if ind == t: pare...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(4, [[0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0]]) == 23
PythonSaga/156
from typing import List def truck_load(cities: int, connections: List[List[int]]) -> int: """in a network of cities and road there are number of trucks that are carrying goods from one city to another city. I have selected to make a load to be carried by a truck from ciy A to city B. I have to find how many ma...
truck_load
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(4, [[0, 12, 14, 0, 0, 0], [12, 0, 1, 0, 0, 0], [14, 1, 0, 20, 10, 0], [0, 0, 20, 0, 0, 5], [0, 0, 10, 0, 0, 15], [0, 0, 0, 5, 15, 0]]) == 10
PythonSaga/157
import sys from typing import List def parcel(cities: int, route: List[List[int]]) -> int: """I have to courier the parcel from my home to my college. I want to know minimum days it will take to reach the parcel to my college. Give: 1. Number of cities in between my home and college. 2. Days t...
parcel
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(2, [[0, 3, 2, 0], [0, 0, 5, 2], [0, 0, 0, 3], [0, 0, 0, 0]]) == 5
PythonSaga/158
from collections import deque from typing import List def blood_flow(organ: int, blood_vessel: List[List[int]]) -> int: """Let's say i want to find max amount of blood that can flow from one organ to another. And in between there are n other organs. organ are connected via blood vessels. Take input from ...
blood_flow
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(4, [[0, 7, 7, 0, 0, 0], [0, 0, 0, 2, 7, 0], [0, 2, 0, 0, 5, 0], [0, 0, 0, 0, 0, 6], [0, 0, 0, 4, 0, 8], [0, 0, 0, 0, 0, 0]]) == 7
PythonSaga/159
from collections import defaultdict from typing import List def data_transfer(routers: int, network_links: List[List[int]]) -> int: """Suppose you want to determine the maximum amount of data that can be transferred from one computer (Computer A) to another (Computer B) in a network. Between these computers,...
data_transfer
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(4, [[0, 7, 7, 0, 0, 0], [0, 0, 0, 2, 7, 0], [0, 2, 0, 0, 5, 0], [0, 0, 0, 0, 0, 6], [0, 0, 0, 4, 0, 8], [0, 0, 0, 0, 0, 0]]) == 7
PythonSaga/160
def divide_100_by(x:int)->str: """Let's say you have function divide(x,y) that returns x/y. Write a function called bind1st(func, value) that can create a one parameter function from this two parameter function? create a new function called divide_100_by(y). Use bind2func to create a function that d...
divide_100_by
def bind1st(func): @wraps(func) def wrapper(value): return func(100, value) return wrapper @bind1st def divide(x, y): return x / y def divide_100_by(y): result = divide(y) return f"100 divided by {y} is {result:.2f}" # Example usage: user_input = int(input("Enter a number: ")) output ...
METADATA = {'author': 'ay','dataset': 'test'} def check(candidate): user_input_1 = 10 output_1 = candidate(user_input_1) assert output_1 == '100 divided by 10 is 10.00' user_input_2 = 3 output_2 = candidate(user_input_2) assert output_2 == '100 divided by 3 is 33.33' user_input_3 = 7 o...
PythonSaga/161
import time from typing import List def math_ops(a: int, b: int) -> List[List[str]]: """Let's say I have two number a and b, and I few functions: 1. mutliply(a, b) 2. divide(a, b) 3. power(a, b) But these function uses loops instead of direct multiplication, division, and power to solve the pr...
math_ops
import time from typing import List def time_decorator(func): def wrapper(a, b): start = time.time_ns() # Capture start time in nanoseconds result = func(a, b) # Call the original function end = time.time_ns() # Capture end time in nanoseconds elapsed = end - start # Calculate el...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(10, 5) == [['50', 'True'], ['2', 'True'], ['100000', 'True']] assert candidate(8, 2) == [['16', 'True'], ['4', 'True'], ['64', 'True']] assert candidate(15, 3) == [['45', 'True'], ['5', 'True'], ['3375', 'True']...
PythonSaga/162
from typing import List def number_plate(number: List[str]) -> List[str]: """I have a bunch of car number plates in the format of 'XX XX XXXX'. I want to print them in sorted order. Also, sometimes there is a prefix 'HS', 'AB', or 'XX' in front and sometimes it is not there. Take input from the user ...
number_plate
def number_plate_decorator(func: Callable[[List[str]], List[str]]) -> Callable[[List[str]], List[str]]: def wrapper(number: List[str]) -> List[str]: # Process each number plate: remove existing prefix and add "Hind" prefix processed = ["Hind " + " ".join(plate.split()[1:]) if plate.split()[0] in ["H...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(["HS 01 1234", "06 1234", "AB 01 1134", "01 1234", "XX 11 1234"]) == ['Hind 01 1134', 'Hind 01 1234', 'Hind 01 1234', 'Hind 06 1234', 'Hind 11 1234'] assert candidate(["AB 12 3456", "XX 09 8765", "HS 05 4321", "03 5...
PythonSaga/163
from typing import List def introduction(n:int ,name: List[str]) -> List[str]: """Utilize decorators and closure to create a name directory using provided information about individuals, including first name, last name, age, and sex. Display their names in a designated format, sorted in ascending order b...
introduction
def name_directory_decorator(func): def wrapper(name: List[List[str]]): # Process the input list: format names and sort by age processed_list = sorted(name, key=lambda x: x[2]) # Sort by age formatted_list = [("Mr. " if person[3] == "m" else "Ms. ") + person[0] + " " + person[1] for person ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([['amit', 'yadav', 23, 'm'], ['amit', 'jain', 12, 'm'], ['ankita', 'did', 23, 'f']]) == ['Mr. amit jain', 'Mr. amit yadav', 'Ms. ankita did'] assert candidate([['john', 'doe', 30, 'm'], ['jane', 'smith', 25, 'f'], [...
PythonSaga/164
from typing import List def mat_sum(n:int, m:int, matrix: List[List[int]]) -> int: """I have an n*m matrix, filled with positive integers. I want to find the path in this matrix, from top left to bottom right, that minimizes the sum of the integers along the path. Try to use decorator and closure to...
mat_sum
def min_path_decorator(func): def wrapper(n, m, matrix): return func(n, m, matrix) return wrapper @min_path_decorator def mat_sum(n: int, m: int, matrix: List[List[int]]) -> int: # Dynamic Programming to calculate the minimum path sum for i in range(n): for j in range(m): if...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(3, 3, [[1, 3, 1], [1, 5, 1], [4, 2, 1]]) == 7 assert candidate(2, 3, [[1, 2, 3], [4, 5, 6]]) == 12 assert candidate(3, 3, [[5, 2, 7], [8, 1, 9], [4, 3, 6]]) == 17 assert candidate(3, 3, [[1, 1, 1], [1, 1, 1]...
PythonSaga/165
from typing import List import concurrent.futures def sum_divisible_by_3(n: int, pairs: List[List[int]]) -> List[int]: """I want to implement concurrency and parallelism in code for faster execution. Take input from the user for n pair of numbers (a,b) where a<b. Print sum of all numbers between a and b ...
sum_divisible_by_3
def sum_divisible_by_3_in_range(pair: List[int]) -> int: """Calculate the sum of numbers divisible by 3 within the given range (a, b], where b is inclusive.""" a, b = pair # Start from the next number if 'a' is not divisible by 3 start = a + 1 if a % 3 != 0 else a return sum(x for x in range(start, ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(2, [[1, 10], [3, 5]]) == [18, 0] assert candidate(3, [[2, 8], [5, 15], [1, 5]]) == [9, 27, 3] assert candidate(1, [[3, 9]]) == [15] assert candidate(4, [[1, 5], [6, 10], [11, 15], [16, 20]]) == [3, 9, 27,...
PythonSaga/166
import threading import concurrent.futures from typing import List def matrix_multiplication(n: int, matrix: List[List[int]]) -> List[List[int]]: """I want to implement matrix multiplication of n matrices each of size 3x3. Each matrix element is [n,n+1,n+2,n+3,n+4,n+5,n+6,n+7,n+8]. But I want to do ...
matrix_multiplication
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(3, [3, 4, 5]) == [ [[3, 4, 5], [6, 7, 8], [9, 10, 11]], [[4, 5, 6], [7, 8, 9], [10, 11, 12]], [[5, 6, 7], [8, 9, 10], [11, 12, 13]], [[114, 126, 138], [156, 174, 192], [198, 222, 246]] ...
PythonSaga/167
import time import multiprocessing import concurrent.futures from typing import List def input_func(a:int, b:int) -> List[str]: """I want to learn how concurrency and parallelism works in python. To do that i want to calculate pow(a,b) using for loops. I want to do this using concurrent.futures and...
input_func
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(2, 1000) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True'] assert candidate(3, 500) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True'] asser...
PythonSaga/168
import concurrent.futures from typing import List def conc_work(n: int, tasks: List[int]) -> List[str]: """I want to learn how concurrent processes work in Python. To do that take multiple tasks and their duration to complete their work. Your goal is to create a program that executes these tasks concurrently ...
conc_work
def simulate_task(duration: int, task_name: str) -> str: """Simulate a task that takes 'duration' seconds to complete.""" print(f"Executing Task {task_name}...") time.sleep(duration) return f"Task {task_name} completed." def conc_work(n: int, tasks: List[int]) -> List[str]: start_time = time.time()...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(4, [3, 5, 2, 4]) == ["Executing Task C...", "Executing Task A...", "Executing Task D...", "Executing Task B...", True] assert candidate(3, [2, 4, 1]) == ["Executing Task C...", "Executing Task A...", "Executing Task...
PythonSaga/169
import concurrent.futures from typing import List def math_tasks(n: int, tasks: List[int]) -> List[str]: """I want to implement concurrency and parallelism in code for faster execution. Take input from user for n tasks and their parameters. Print the result of each task. If parameters are invalid return "...
math_tasks
def perform_task(param: int) -> str: """Simulate a math task that computes the sum of numbers up to 'param'. If 'param' is invalid, returns 'Not Done'.""" if param < 0: return "Not Done" result = sum(range(param + 1)) # Example task: sum of numbers up to 'param' return "Done" def math_task...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(4, [1000000, 500000, 750000, 200000]) == [ "Performing Task A...", "Performing Task B...", "Performing Task C...", "Performing Task D...", "Done", "Done", "Done", ...
PythonSaga/170
from typing import List def input_for_class1(coffs:List[List[int]])->List[str]: """Create a Python class named Polynomial that represents a polynomial of a single variable. The Polynomial class should support the following operations: 1. Initialization: The class should be initialized with a list of coef...
input_for_class1
class Polynomial: def __init__(self, coeffs: List[int]): self.coeffs = coeffs def __str__(self): terms = [] n = len(self.coeffs) for i, coeff in enumerate(self.coeffs): power = n - i - 1 if coeff == 0: continue if power == 0: ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate([[1, -3, 0, 2], [2, 0, 1]]) == ['x^3 - 3x^2 + 2', '2x^2 + 1', 'x^3 - x^2 + 3', 'x^3 - 5x^2-1'] assert candidate([[1, 2, 3], [3, 2, 1]]) == ['x^2 + 2x + 3', '3x^2 + 2x + 1', '4x^2 + 4x + 4', '-2x^2 +2'] assert ca...
PythonSaga/171
from typing import List def input_for_class2(entries:List[str])->str: """I want to see magic using class and object. Let's say i have a class named "Person". In object i will pass name, id nummber, salary and position. Then i want to print all the information of that object. But twist is i want class Perso...
input_for_class2
class Person: def __init__(self, name: str, id_number: int): self.name = name self.id_number = id_number class Employee(Person): def __init__(self, name: str, id_number: int, salary: int, position: str): super().__init__(name, id_number) self.salary = salary self.positio...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(["John", "1234", "10000", "Manager"]) == "My name is John, My id number is 1234, My salary is 10000 and my position is Manager." assert candidate(["Ram", "12223", "20000", "CEO"]) == "My name is Ram, My id number is...
PythonSaga/172
def input_for_class3(typess:str)->str: """I want to test my knowledge of polymorphism. I want to create a car catalog using classes and polymorphism. On top we have class Car, with description "Welcome to car catalog, here you can find all the cars you need." Let's say I have class name sedan, suv, c...
input_for_class3
class Car: def __init__(self): self.description = "Welcome to car catalog, here you can find all the cars you need." def get_description(self): return self.description class Sedan(Car): def __init__(self): super().__init__() self.description += " This is a sedan car with 4 ...
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("sedan") == "Welcome to car catalog, here you can find all the cars you need. This is a sedan car with 4 doors and 5 seats, usage is for family." assert candidate("suv") == "Welcome to car catalog, here you can fin...
PythonSaga/173
from typing import List def input_for_class4(data:List[str])->List[str]: """Create a Python class named BankAccount that represents a bank account. The BankAccount class should support the following operations: 1. Initialization: The class should be initialized with an account holder's name and an initia...
input_for_class4
from typing import List class BankAccount: def __init__(self, name: str, initial_balance: float): self.name = name self.balance = initial_balance def deposit(self, amount: float): self.balance += amount def withdraw(self, amount: float): if amount > self.balance: ...
def check(candidate): assert candidate(["John", "1000", "Deposit", "500", "Withdraw", "200", "Balance", "Exit"]) == ["Your current balance is 1300"] assert candidate(["Alice", "1500", "Deposit", "300", "Balance", "Withdraw", "200", "Exit"]) == ["Your current balance is 1800", "Your current balance is 1600"] ...
PythonSaga/174
from typing import List def input_for_class5(data:List[str])->List[str]: """You are tasked with designing a Python class to manage and monitor activities at a construction site. The class should encapsulate various aspects of construction management. Implement the following functionalities: Initializatio...
input_for_class5
class ConstructionSite: def __init__(self, name: str, initial_budget: float): self.name = name self.budget = initial_budget self.material_inventory = {} self.workers = {} def add_material(self, material_name: str, quantity: int): if material_name in self.material_invento...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(['IIT', '100000', 'material addition', 'cement', '100', 'material addition', 'bricks', '1000', 'material addition', 'sand', '500', 'worker addition', 'John', '1', 'worker addition', 'Mike', '2', 'worker addition', 'Mary', '3', 's...
PythonSaga/175
from typing import List def input_for_cont1(data:str)->List[str]: """I want to create dummy context manager. Here's it should be: 1. create class ContextManager 2. When I call it, it should print "init method called" 3. When I call it with "with" statement, it should print "enter method called" ...
input_for_cont1
class ContextManager: def __init__(self, text: str): self.text = text print("init method called") def __enter__(self): print("enter method called") return self def __exit__(self, exc_type, exc_val, exc_tb): print(self.text) print("exit method called") def i...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate("Hello i'm in context manager") == ["init method called", "enter method called", "Hello i'm in context manager", "exit method called"]
PythonSaga/176
from decimal import Decimal, getcontext def input_for_cont2(data:str)->str: """I'm working in space and astronomy institute where calculations need to be done in a very precise way. I'm working on a project where I need to calculate. Small part of it is division of two numbers which need to be very preci...
input_for_cont2
# Set the precision getcontext().prec = n # Perform the division using Decimal for high precision result = Decimal(a) / Decimal(b) # Reset the precision to default (28) to avoid side effects getcontext().prec = 28 return str(result) # Convert the result to a string
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate("1,42,42") == "0.0238095238095238095238095238095238095238095" assert candidate("3,7,9") == "0.428571429" assert candidate("3,7,9") == "0.428571428571428571428571428571429"
PythonSaga/177
from decimal import Decimal, getcontext def input_for_cont3(data:str)->str: """I'm working in science lab where experminets and their calculations done in a very precise way. I'm working on a project where I need to calculate. Small part of it is division of two numbers which need to be very precise upto...
input_for_cont3
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate("1,42,42") == "0.0238095238095238095238095238095238095238095" assert candidate("3,7,9") == "0.428571429" assert candidate("3,7,9") == "0.428571428571428571428571428571429"
PythonSaga/178
def divide(x:int, y:int) -> str: """I have few codes which may or may not run successfully. I want to know what error it will print if it fails to run. And if it runs successfully, it should print the output. The code if for division of two numbers. Take two numbers as input from user and divide the...
divide
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate(2,5) == "0.4" assert candidate(2,0) == "integer division or modulo by zero" assert candidate(1,5) == "0.2" assert candidate(11,0) == "integer division or modulo by zero"
PythonSaga/179
def write_file(first:str, second:str) -> str: """I have a file named dummy.txt. I want to write some text in it i.e. "This is a dummy file." Later I want to write some more text in it i.e. "This is a dummy file2." But when I run the code, it gives me an error. I want to know what error it is, please print i...
write_file
METADATA = { 'author': 'ay', 'dataset': 'test' } def check(candidate): assert candidate("This is a dummy file.", "This is a dummy file2.") == "I/O operation on closed file."
PythonSaga/180
def max_capacity(n:int, m:int) -> int: """I have 2 pack of floor of n and m kgs. I have to purchase a scope of such capacity that it can be used for both bags. But the idea is the number of scoops to empty both bag should be natural number respectively. Also the scope should be of maximum capacity as possib...
max_capacity
if b == 0: return a return max_capacity(b, a % b)
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(3,5) == 1 assert candidate(4,20) == 4 assert candidate(6,15) == 3 assert candidate(26,39) == 13
PythonSaga/181
def max_stencils(n:int, a:int, b:int, c:int) -> int: """I have a wall of length n, and 3 stencils of length a, b, and c. I have to paint the wall using these stencils. But in such a way that the number of stencils used to paint the wall should be maximum to bring out the best design. Also, the length of the...
max_stencils
if n == 0 : return 0 if n <= -1 : return -1 res = max(max_stencils(n-a,a,b,c), max_stencils(n-b,a,b,c), max_stencils(n-c,a,b,c)) if res == -1 : return -1 return res + 1
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(23, 11, 9, 12) == 2 assert candidate(17, 10, 11, 3) == 3 assert candidate(18, 11, 9, 3) == 6 assert candidate(21, 11, 9, 2) == 7
PythonSaga/182
def round_chairs(n:int, k:int) -> int: """I am playing a game of round chairs with my friends. Where n chairs are arranged in a circle. Every time a game starts the kth chair is removed from the circle and the game continues. Until only one chair is left. I have to find out the position of the last chair le...
round_chairs
if (n == 1): return 1 else: return (round_chairs(n - 1, k) + k-1) % n + 1
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate(14, 2) == 13 assert candidate(7, 3) == 4 assert candidate(10, 2) == 5 assert candidate(11, 5) == 8
PythonSaga/183
def qwerty_phone(key_presses: list) -> list: """I saw the qwerty phones and i was thinking about the number of key presses to type a word. So, now I want to find the numbers of words that can be typed using the given number of key presses. My keypad looks like this: 1:{},2:{'a','b','c'},3:{'d','e','f'},...
qwerty_phone
digit_map = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz', } def qwerty_phone(input): input = str(input) ret = [''] for char in input: letters = digit_map.get(char, '') ret = [prefix+letter for prefix in ret for letter i...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate([2,3,4]) == ['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi'] assert candidate([1]) =...
PythonSaga/184
def match_ptr(s:str, ptr:str) -> bool: """Given an string s and a pattern ptr, implement pattern matching with support for '+' and '-' where: '+' Matches any single character. '-' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not p...
match_ptr
i, j, si, m = 0, 0, -1, 0 while i < len(s): if j < len(p) and (s[i] == p[j] or p[j] == '+'): j += 1 i += 1 elif j < len(p) and p[j] == '-': si = j m = i j += 1 elif si != -1: j = si + 1 m += 1 i = m else: return False while j < len(...
METADATA = {'author': 'ay', 'dataset': 'test'} def check(candidate): assert candidate('aa', 'a+') == True assert candidate('aa','a') == False assert candidate('aab', '-a-') == True assert candidate('aab', '-a') == False