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 income tax of a person i.e 10% of the income
3. vehicleTax: calculate the vehicle tax of a vehicle i.e 5% of the vehicle value
Take input from user for house value, income and vehicle value and print the tax for each of them.
Along with this also take name of the person and print the name of the person before printing the tax.
Example:
Input: Jhon, {house value: 500000, income: 1000000, vehicle value: 100000}
Output: {house tax: 10000, income tax: 100000, vehicle tax: 5000}"""
| 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.05}
person_tax = Tax(user)
result = {
**person_tax.LandTax(house_value),
**person_tax.IncomeTax(income),
**person_tax.VehicleTax(vehicle_value)
}
return result | 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}
assert candidate("Charlie", 600000, 150000, 90000) == {'house tax': 12000, 'income tax': 15000, 'vehicle tax': 4500}
assert candidate("David", 350000, 90000, 80000) == {'house tax': 7000, 'income tax': 9000, 'vehicle tax': 4000} |
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: +, -, *, /
There are few paranthesis: (,{,[,],},)
Take input from user and return "Balanced" or "Not Balanced" accordingly.
Example:
Input: (a+b)*c
Output: Balanced
Input: (a+b)*c)
Output: Not Balanced
Input: (a+b)c
Output: Not Balanced """
| 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 '({[':
# Check for operand followed by '(' without an operator in between
if last.isalnum():
return 'Not Balanced'
self.stack.append(char)
elif char in ')}]':
if not self.stack or self.stack[-1] != self.pairs[char]:
return 'Not Balanced'
self.stack.pop()
elif char.isalnum() and last in ')]}':
# Check for ')' followed by an operand without an operator in between
return 'Not Balanced'
last = char # Update the last character processed
# Check for any unmatched opening parentheses
if self.stack:
return 'Not Balanced'
return 'Balanced'
def input_func2(eqn: str) -> str:
checker = CheckBalance(eqn)
return checker.is_balanced() | 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 list of both orders and also print the order
with maximum amount.
Example:
Input: [1,2,3,4,5,6], [10,20,30]
Output: ([1,2,3,4,5,6,10,20,30], "Order 2 > Order 1")"""
| 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_other = sum(other.order_list)
if total_amount_self > total_amount_other:
return f"Order 1 > Order 2"
elif total_amount_self < total_amount_other:
return f"Order 2 > Order 1"
else:
return "Order 1 = Order 2"
def input_func3(lst1: List[int], lst2: List[int]) -> Tuple[List[int], str]:
order1 = Orders(lst1)
order2 = Orders(lst2)
merged_order = order1 + order2
comparison_result = order1 > order2
return merged_order.order_list, comparison_result | 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, 5, 6]) == ([1, 2, 3, 4, 5, 6], "Order 2 > Order 1")
assert candidate([], [10, 20, 30]) == ([10, 20, 30], "Order 2 > Order 1") |
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
2. Cat, type of animal: mammal, sound: meow
3. Duck , type of animal: bird, sound: quack
4. snake, type of animal: reptile, sound: hiss
Take input from user and display the name of animal and its type and sound.
Try to use inheritance to reduce the number of lines of code.
Example:
Input: "dog"
Output: "Name of animal is dog, it belongs to mammal family and it barks."
Input: "snake"
Output: "Name of animal is snake, it belongs to reptile family and it hisses."""
| 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}."
class Dog(Animal):
def __init__(self, name: str):
super().__init__(name, "mammal", "barks")
class Cat(Animal):
def __init__(self, name: str):
super().__init__(name, "mammal", "meows")
class Duck(Animal):
def __init__(self, name: str):
super().__init__(name, "bird", "quacks")
class Snake(Animal):
def __init__(self, name: str):
super().__init__(name, "reptile", "hisses")
def input_func4(animal: str) -> str:
animal_class = None
if animal.lower() == "dog":
animal_class = Dog(animal)
elif animal.lower() == "cat":
animal_class = Cat(animal)
elif animal.lower() == "duck":
animal_class = Duck(animal)
elif animal.lower() == "snake":
animal_class = Snake(animal)
if animal_class:
return animal_class.display_info()
else:
return "Unknown animal." | 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 animal is duck, it belongs to bird family and it quacks."
assert candidate("snake") == "Name of animal is snake, it belongs to reptile family and it hisses." |
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 the distance from origin
Also create other classes named North, South, East, West that inherit from Distance
Take input from the user in the form of Direction and Distance until the user enters 'stop'
Return the distance from origin
Example:
Input: [[N,5],[E,3],[S,5],[stop]]
Output: 3
Input: [[N,5],[N,7],[S,5],[stop]]
Output: 7"""
| 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
elif direction == 'E':
self.x += distance
elif direction == 'W':
self.x -= distance
def get_distance_from_origin(self) -> int:
# Manhattan distance from the origin
return abs(self.x) + abs(self.y)
def input_func5(dir: List[Tuple[str, int]]) -> int:
distance_obj = Distance()
for command in dir:
if command[0].lower() == 'stop': # Using lower() to make it case-insensitive
break
direction, dist = command
distance_obj.update_position(dist, direction)
return distance_obj.get_distance_from_origin() | 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', 8], ['W', 4], ['S', 3], ['stop']]) == 5 |
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 diagonal with the values of the triangle below it like a mirror image swap.
Take the value of n from the user and take n rows of input from the user and Print the 2-D array obtained in a matrix layout.
Example:
Input: 3,[[1,2,4],[5,9,0],[3,1,7]]
Output: [[1,5,3],[2,9,1],[4,0,7]]"""
| 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, 16]]) == [[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]]
assert candidate(3, [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) == [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
assert candidate(1, [[9]]) == [[9]] |
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.
2. Choose either row/column of the selected matrix.
3. Increment every element of the selected row/column by 1.
Take the value of n and m from the user and take two input matrices from the user.
Print the number of changes required to make M1 equal to M2. if it is not possible print -1.
Example:
Input: 2,2,[[1,1],[1,1]],[[1,2],[3,4]] # Here 2 is n and 2 is m. and then two matrices of order 2*2.
Output: 3
Input: 2,2,[[1,1],[1,1]],[[1,0],[0,-1]] # Here 2 is n and 2 is m. and then two matrices of order 2*2.
Output: -1"""
| 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, 2, [[1, 2], [3, 4]], [[2, 4], [3, 6]]) == -1 |
|
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 maximum prize i.e sum of all the elements of the submatrix.
Example:
Input: 4,5,[[1,2,-1,-4,-20],[-8,-3,4,2,1],[3,8,10,1,3],[-4,-1,1,7,-6]] # Here 4 is n and 5 is m. and then matrix of order 4*5.
Output: 29"""
| 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')
# Row combination loop
for startRow in range(n):
temp = [0] * m
for row in range(startRow, n):
# Calculate cumulative sum for the current row combination
for col in range(m):
temp[col] += matrix[row][col]
# Apply Kadane's algorithm to find max sum for this row combination
maxSum = max(maxSum, kadane(temp))
return maxSum | 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
assert candidate(2, 3, [[1, 2, 3], [-4, 5, 6]]) == 16 |
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 user and Print the maximum number of cells that you can visit in the matrix by starting from some cell.
Example:
Input: 2,3,[[3,1,6],[-9,5,7]] # Here 2 is n and 3 is m. and then matrix of order 2*3.
Output: 4
Input: 2,2,[[4,2],[4,5]] # Here 2 is n and 2 is m. and then matrix of order 2*2.
Output: 2"""
| 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 di, dj in directions:
x, y = i + di, j + dj
# Move to the cell (x, y) if it's within the matrix bounds and has a greater value
if 0 <= x < n and 0 <= y < m and matrix[x][y] > matrix[i][j]:
max_path = max(max_path, 1 + dfs(x, y, n, m, matrix, dp))
dp[i][j] = max_path # Memoize the result
return max_path
def longest_path(n: int, m: int, matrix: List[List[int]]) -> int:
dp = [[0 for _ in range(m)] for _ in range(n)] # Initialize the dp matrix
max_length = 0
for i in range(n):
for j in range(m):
max_length = max(max_length, dfs(i, j, n, m, matrix, dp))
return max_length | 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, 0) and ending in the bottom-right corner (m - 1, n - 1),
find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.
Return the maximum non-negative product modulo 10^9 + 7. If the maximum product is negative, return -1.
Take the value of n and m as input from the user and then take the input matrix of size n*m from the user.
Example:
Input: 3,3,[[1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
Output: -1
Input: 2,2,[[1,2],[0,-4]]
Output: 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, 1, 1]]) == 2 |
|
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.
Example:
Input: [10,10] # Given in level order traversal
Output: True
Input: [1,4,3,5]
Output: False"""
| 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
# Value of left child, 0 if there is no left child
left_val = arr[left] if left < len(arr) else 0
# Value of right child, 0 if there is no right child
right_val = arr[right] if right < len(arr) else 0
# Check the sum property for the current node and recursively check for children
return (arr[index] == left_val + right_val) and is_sum_tree(arr, left) and is_sum_tree(arr, right)
def binary_tree(arr: List[int]) -> bool:
# The root is at index 0, start checking from there
return is_sum_tree(arr) | 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.
Example:
Input: 3,[8,5,9,2,6,null,10] # Given in level order traversal
Output: [2,5] # Floor and ceil of 3 in the given bst"""
| 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] == num:
return num, num
# Update floor and ceil
if arr[index] < num:
floor = arr[index]
return find_floor_ceil(arr, num, 2 * index + 2, floor, ceil) # Go to the right child
else:
ceil = arr[index]
return find_floor_ceil(arr, num, 2 * index + 1, floor, ceil) # Go to the left child
def floor_ceil(num, arr):
return list(find_floor_ceil(arr, num)) | 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:
Input: [3,1,5],[4,2,6] # Given in level order traversal
Output: [1,2,3,4,5,6]
Input: [8,2,10,1],[5,3,null,0]
Output: [0,1,2,3,5,8,10]"""
| 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 * index + 2, inorder)
def merge_inorder_traversals(inorder1, inorder2):
merged = []
i = j = 0
while i < len(inorder1) and j < len(inorder2):
if inorder1[i] < inorder2[j]:
merged.append(inorder1[i])
i += 1
else:
merged.append(inorder2[j])
j += 1
# Append remaining elements
merged.extend(inorder1[i:])
merged.extend(inorder2[j:])
return merged
def merge_bst(arr1, arr2):
inorder1 = []
inorder2 = []
inorder_from_level_order(arr1, 0, inorder1)
inorder_from_level_order(arr2, 0, inorder2)
return merge_inorder_traversals(inorder1, inorder2) | 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 candidate(input_data3, input_data4) == [0, 1, 2, 3, 5, 8, 10]
# Test Case 3:
input_data5 = [2,1,3]
input_data6 = [4]
assert candidate(input_data5, input_data6) == [1,2,3,4]
# Test Case 4:
input_data7 = [4, 2, 7,None, 3]
input_data8 = [5,1,7]
assert candidate(input_data7, input_data8) == [1, 2, 3, 4, 5, 7, 7] |
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 subtrees must also be binary search trees.
Take input from the user and check if it is a valid BST or not.
Example 1:
Input: [2,1,3] # Given in level order traversal
Output: True
Input: [5,1,4,None,None,3,6]
Output: False
Input: [5,1,6,None,None,5.5,7]
Output: True""" | 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:
root.right = insert_bst(root.right, value)
return root
def is_valid_bst(arr: List[int]) -> bool:
if not arr:
return True
root = TreeNode(arr[0])
queue = [root]
index = 1
while queue and index < len(arr):
current = queue.pop(0)
if arr[index] is not None:
current.left = TreeNode(arr[index])
queue.append(current.left)
index += 1
if index < len(arr) and arr[index] is not None:
current.right = TreeNode(arr[index])
queue.append(current.right)
index += 1
def is_bst(node, min_val=float('-inf'), max_val=float('inf')):
if not node:
return True
if not min_val < node.value < max_val:
return False
return is_bst(node.left, min_val, node.value) and is_bst(node.right, node.value, max_val)
return is_bst(root) | 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) == True
input_data4 = [10, 5, 15, None, None, 12, 20]
assert candidate(input_data4) == True |
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 represented by the number of edges between them.
Take input from user for binary tree and return the length of the longest path, where each node in the path has the same value.
Example 1:
Input: root = [5,4,5,1,1,5,5] # Level order traversal
Output: 2
Input: root = [2,4,5,4,4,5] # Level order traversal
Output: 2""" | 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 children
nonlocal max_length
max_length = max(max_length, left_len + right_len)
# Return the length of the path extending from the current node
if arr[index] == value:
return 1 + max(left_len, right_len)
return 0
if not arr:
return 0
max_length = 0
dfs(0, arr[0])
return max_length | 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.
Example:
Input: [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17]
Output: [17, 15, 13, 9, 6, 5, 10, 4, 8, 3, 1]""" | 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 largest so far
if right < n and arr[largest] < arr[right]:
largest = right
# If largest is not root
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i] # Swap
# Heapify the root
heapify(arr, n, largest)
def max_heapify(arr: List[int]) -> List[int]:
n = len(arr)
# Build a max heap
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
return arr | 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, 5, 2, 1]
input_data3 = [20, 15, 10, 5, 12, 14, 18, 8, 7, 2, 3, 1]
assert candidate(input_data3) == [20, 15, 18, 8, 12, 14, 10, 5, 7, 2, 3, 1]
input_data4 = [25, 30, 40, 20, 10, 35, 18, 15, 12, 8, 5]
assert candidate(input_data4) == [40, 30, 35, 20, 10, 25, 18, 15, 12, 8, 5] |
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 ropes and their lengths as input from user and print the minimum cost.
Use heap concept to solve this problem.
Example:
Input: 4, [5, 4, 3, 7]
Output: 38
Input: 3, [1, 2, 3]
Output: 9""" | 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 + second
# Add the cost
total_cost += connected_rope
# Put the resulting rope back into the heap
heapq.heappush(arr, connected_rope)
return total_cost | 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, 4]
assert candidate(*input_data3) == 64
# Test Case 4:
input_data4 = 2, [1, 5]
assert candidate(*input_data4) == 6 |
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 concept to solve this problem.
Example 1:
Input: 'aaabc'
Output: True
Input: 'aa'
Output: False """ | 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:
# Extract the two most frequent characters
freq1, char1 = heapq.heappop(max_heap)
freq2, char2 = heapq.heappop(max_heap)
# Append the characters to the result
result.extend([char1, char2])
# Decrement the frequencies and push back into the heap if the frequency is not zero
if freq1 + 1 != 0:
heapq.heappush(max_heap, (freq1 + 1, char1))
if freq2 + 1 != 0:
heapq.heappush(max_heap, (freq2 + 1, char2))
# If there is only one character left, append it to the result
if max_heap:
result.append(max_heap[0][1])
# Check if the result is a valid rearrangement
return len(result) == len(s) | 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 candidate(input_data3) == True
# Test Case 4:
input_data4 = 'abcde'
assert candidate(input_data4) == True |
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, 'e': 16, 'f': 45}
Output: {'a': '1100', 'b': '1101', 'c': '100', 'd': '101', 'e': '111', 'f': '0'}
""" | 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()]
heapq.heapify(min_heap)
while len(min_heap) > 1:
left = heapq.heappop(min_heap)
right = heapq.heappop(min_heap)
merged_node = Node(None, left.freq + right.freq)
merged_node.left = left
merged_node.right = right
heapq.heappush(min_heap, merged_node)
return min_heap[0]
def generate_huffman_codes(root, code="", huff_codes=None):
if huff_codes is None:
huff_codes = {}
if root:
if not root.left and not root.right:
huff_codes[root.char] = code
generate_huffman_codes(root.left, code + "0", huff_codes)
generate_huffman_codes(root.right, code + "1", huff_codes)
def huff_encode(n: int, d: Dict) -> Dict:
if n < 2:
return {}
# Build the Huffman tree
root = build_huffman_tree(d)
# Generate Huffman codes
huff_codes = {}
generate_huffman_codes(root, "", huff_codes)
return huff_codes | 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 = 4, {'x': 2, 'y': 2, 'z': 2, 'w': 2}
assert candidate(*input_data2) == {'z': '00', 'x': '01', 'w': '10', 'y': '11'}
# Test Case 3:
input_data3 = 3, {'p': 1, 'q': 2, 'r': 3}
assert candidate(*input_data3) == {'r': '0', 'p': '10', 'q': '11'}
# Test Case 4:
input_data4 = 2, {'A': 10, 'B': 20}
assert candidate(*input_data4) == {'A': '0', 'B': '1'} |
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, 5, 7], [2, 4, 6, 8], [0, 9, 10, 11]]
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10, 11]""" | 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 to the next element in the same list
if index_in_list + 1 < len(lists[list_index]):
heapq.heappush(min_heap, (lists[list_index][index_in_list + 1], list_index, index_in_list + 1))
return result | 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]]
assert candidate(*input_data2) == [-1, 0, 2, 3, 4, 5, 6, 8]
# Test Case 3:
input_data3 = 4, [[10, 15, 20, 25], [1, 5, 7, 30], [4, 8, 11, 13], [3, 6, 9, 12]]
assert candidate(*input_data3) == [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 20, 25, 30]
# Test Case 4:
input_data4 = 3, [[], [2, 4, 6, 8], [0, 9, 10, 11]]
assert candidate(*input_data4) == [0, 2, 4, 6, 8, 9, 10, 11] |
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 using the given word.
Example:
Input: ['hello', 'hell', 'hi', 'how', 'are', 'you', 'hero', 'hey'], 'he'
Output: ['hello', 'hell', 'hero', 'hey'] """ | 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
def search_prefix(root, prefix):
node = root
for char in prefix:
if char not in node.children:
return []
node = node.children[char]
suggestions = []
traverse_trie(node, prefix, suggestions)
return suggestions
def traverse_trie(node, current_word, suggestions):
if node.is_end_of_word:
suggestions.append(current_word)
for char, child_node in node.children.items():
traverse_trie(child_node, current_word + char, suggestions)
def autoComplete(words: List[str], word: str) -> List[str]:
root = TrieNode()
for w in words:
insert_word(root, w)
suggestions = search_prefix(root, word)
return suggestions | 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_words2 = ['apple', 'apricot', 'banana', 'apex', 'apologize', 'apartment']
input_word2 = 'ap'
assert candidate(input_words2, input_word2) == ['apple', 'apricot', 'apex', 'apologize', 'apartment']
# Test Case 3:
input_words3 = ['python', 'programming', 'pyramid', 'pyro', 'pyrite', 'puzzle']
input_word3 = 'py'
assert candidate(input_words3, input_word3) == ['python', 'programming', 'pyramid', 'pyro', 'pyrite']
# Test Case 4:
input_words4 = ['car', 'cat', 'cart', 'caramel', 'cabbage', 'camera']
input_word4 = 'ca'
assert candidate(input_words4, input_word4) == ['car', 'cat', 'cart', 'caramel', 'cabbage', 'camera'] |
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 should be the shortest prefix out of all railway stations renamed prior to this.
If some city has same name, then prefix will be the name with suffix as the count of occurence of that city prior to this and including this, seperated with spaces.
Take a name of city as input from user and print the station code as output.
Example 1:
Input: ['Delhi', 'Mumbai', 'Chennai', 'Kolkata', 'Dehradun', 'Delhi']
Output: ['D', 'M', 'C', 'K', 'Deh', 'Delhi2] """
| 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:
# For the first occurrence, find a unique prefix
prefix = ""
for i in range(1, len(city) + 1):
prefix = city[:i]
if prefix not in used_codes:
break
codes.append(prefix)
used_codes.add(prefix)
else:
# For subsequent occurrences, use the full name with a count
code = f"{city}{city_count[city]}"
codes.append(code)
used_codes.add(code)
return codes | 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', 'Jammu', 'Delhi', 'Jammu', 'Dehradun']
assert candidate(input_cities2) == ['S', 'Sa', 'J', 'D', 'Jammu2', 'Deh']
# Test Case 3:
input_cities3 = ['NewYork', 'NewDelhi', 'NewJersey', 'NewYork', 'NewJersey', 'NewDelhi']
assert candidate(input_cities3) == ['N', 'NewD', 'NewJ', 'NewYork2', 'NewJersey2', 'NewDelhi2']
# Test Case 4:
input_cities4 = ['Tokyo', 'Osaka', 'Kyoto', 'Tokyo', 'Kyoto', 'Osaka', 'Kyoto']
assert candidate(input_cities4) == ['T', 'O', 'K', 'Tokyo2', 'Kyoto2', 'Osaka2', 'Kyoto3'] |
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 input from user and return the maximum possible value of Bitwise Xor of all the elements in the subsequence.
Example:
Input: [8, 1, 2, 12]
Output: 14
Input: [1, 2, 3, 4]
Output: 7""" | 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):
max_xor = float('-inf')
for num in nums:
current_xor = 0
node = root
for i in range(31, -1, -1):
bit = (num >> i) & 1
opposite_bit = 1 - bit
if opposite_bit in node.children:
current_xor |= (1 << i)
node = node.children[opposite_bit]
else:
node = node.children[bit]
max_xor = max(max_xor, current_xor)
return max_xor
def max_xor(nums: List[int]) -> int:
root = TrieNode()
for num in nums:
insert(num, root)
return find_max_xor(nums, root) | 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]
assert candidate(input_nums3) == 30
# Test Case 4:
input_nums4 = [7, 3, 5, 2, 10, 8]
assert candidate(input_nums4) == 15 |
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 palindrome pairs.
Example:
Input: ['code', 'edoc', 'da', 'd']
Output: [['code', 'edoc'], ['edoc', 'code'], ['da', 'd']]
Input: ['abcd','dcba','lls','s','sssll']
Output: [['abcd', 'dcba'], ['dcba', 'abcd'], ['lls', 'sssll'], ['s', 'lls']]""" | 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_palindrome(concat_word):
result.append([words[i], words[j]])
return result | 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_words2) == [['dcba', 'abcd'], ['s', 'lls'], ['sssll', 'lls']]
# Test Case 3:
input_words3 = ['race', 'car', 'level', 'deified', 'python']
assert candidate(input_words3) == [['race', 'car'], ['level', 'deified']]
# Test Case 4:
input_words4 = ['bat', 'tab', 'noon', 'moon', 'hello']
assert candidate(input_words4) == [['bat', 'tab'], ['noon', 'moon']] |
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 horizontally or vertically neighboring.
The same letter cell may not be used more than once in a word.
Take a matrix and a list of words as input from user and print all the words that can be formed from the matrix.
Example 1:
Input: 4,4,[[o,a,a,n],[e,t,a,e],[i,h,k,r],[i,f,l,v]],['oath','pea','eat','rain'] # row, col, matrix, words
Output: ['oath','eat']""" | 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
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
if is_valid(board, visited, new_row, new_col) and board[new_row][new_col] in trie:
visited[new_row][new_col] = True
dfs(board, visited, new_row, new_col, current_word + board[new_row][new_col], trie[board[new_row][new_col]], result)
visited[new_row][new_col] = False
def build_trie(words):
trie = {}
for word in words:
node = trie
for char in word:
node = node.setdefault(char, {})
node['#'] = None
return trie
def find_words(board, words):
trie = build_trie(words)
result = []
visited = [[False] * len(board[0]) for _ in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] in trie:
visited[i][j] = True
dfs(board, visited, i, j, board[i][j], trie[board[i][j]], result)
visited[i][j] = False
return result
def cross_words(n:int, m:int, board: List[List[str]], words: List[str]) -> List[str]:
return find_words(board, words) | 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']
# Test Case 2:
input_board2 = [['a','b'],['c','d']]
input_words2 = ['ab', 'cb', 'ad', 'bd', 'ac', 'ca', 'da', 'cd', 'dc']
assert candidate(2, 2, input_board2, input_words2) == ['ab', 'ac', 'bd', 'cd', 'ca', 'dc']
# Test Case 3:
input_board3 = [['a','b','c'],['d','e','f'],['g','h','i']]
input_words3 = ['abc', 'def', 'ghi', 'cfh', 'dea']
assert candidate(3, 3, input_board3, input_words3) == ['abc', 'def', 'ghi']
# Test Case 4:
input_board4 = [['a','b','c'],['d','e','f'],['g','h','i']]
input_words4 = ['abcfedghi']
assert candidate(3, 3, input_board4, input_words4) == ['abcfedghi'] |
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 items.
Take input from the user for n items and the capacity of the bag. and return the maximum value of the transferred items.
Example:
Input: 3, [[60, 10], [100, 20], [120, 30]], 50
Output: 240
Input: 2, [[60, 10], [100, 20]], 50
Output: 160""" | 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 value of the transferred items
for ratio, value, weight in items_with_ratio:
if capacity >= weight:
# If the knapsack can carry the entire item, take all of it
max_value += value
capacity -= weight
else:
# If the knapsack cannot carry the entire item, take the fractional part
max_value += ratio * capacity
break # The knapsack is now full
return max_value | 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 = 50
assert candidate(2, input_items2, input_capacity2) == 30
# Test Case 3:
input_items3 = [[40, 10], [30, 5], [50, 15]]
input_capacity3 = 20
assert candidate(3, input_items3, input_capacity3) == 87
# Test Case 4:
input_items4 = [[25, 7], [15, 5], [30, 10], [10, 2], [5, 1]]
input_capacity4 = 15
assert candidate(5, input_items4, input_capacity4) == 55 |
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 job takes 1 unit of time to complete and only one job can be scheduled at a time.
Take input from the user for the number of jobs and their deadline and profit. and return the maximum profit and number of jobs done.
Example:
Input: 4, [[4, 20], [1, 10], [1, 40], [1, 30]]
Output: [60, 2]"""
| 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 # To calculate the total profit
# Schedule jobs
for deadline, profit in jobs:
for slot in range(min(deadline, max_deadline) - 1, -1, -1):
if not slots[slot]: # If the slot is free
slots[slot] = True # Mark the slot as occupied
job_count += 1 # Increment the job count
total_profit += profit # Add the profit
break # Break after scheduling the job
return [total_profit, job_count] | 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) == [180, 4]
# Test Case 3:
input_jobs3 = [[1, 10], [2, 15], [3, 5], [1, 30], [4, 25]]
assert candidate(5, input_jobs3) == [75, 4]
# Test Case 4:
input_jobs4 = [[1, 5], [2, 10], [3, 15], [4, 20], [5, 25]]
assert candidate(5, input_jobs4) == [75, 5] |
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 for each edge will be given for the tile. In short, we need to choose such a sequence of cutting such that cost is minimized.
Take input from user p, q and cost of breaking each edge both horizontal and vertical. and return the minimum cost of cutting.
Example:
Input: 6, 4, [[2, 1, 3, 1, 4], [4, 1, 2]]
Output: 42"""
| 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 order
all_cuts = sorted(horizontal_cuts + vertical_cuts, key=lambda x: x[0], reverse=True)
# Initialize the number of segments in each direction
horizontal_segments = 1
vertical_segments = 1
total_cost = 0
for cost, cut_type in all_cuts:
if cut_type == 'h':
# The cost of a horizontal cut is multiplied by the current number of vertical segments
total_cost += cost * vertical_segments
horizontal_segments += 1
else:
# The cost of a vertical cut is multiplied by the current number of horizontal segments
total_cost += cost * horizontal_segments
vertical_segments += 1
return total_cost | 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 list of numbers and value X and return the maximum number of equal elements possible for the list.
Example:
Input: [5, 5, 3, 1], 5
Output: 3
Input: [2, 4, 9], 3
Output: 2"""
| 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 # Slide the window forward if the total increments exceed k
# Step 4: Update the maximum number of equal elements
max_equal = max(max_equal, i - j + 1)
return max_equal | 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(nums3, k3) == 1
# Test Case 4:
nums4, k4 = [10, 10, 10, 10, 10], 2
assert candidate(nums4, k4) == 5 |
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:
Input: '313515'
Output: '531135'
Input: '123'
Output: 'not possible'"""
| 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 possible"
middle_digit = str(digit)
count -= 1
left_half.extend([str(digit)] * (count // 2))
# Build the right half by reversing the left half
right_half = left_half[::-1]
# Combine the left half, middle digit (if any), and the right half
palindrome = "".join(left_half + [middle_digit] + right_half)
return palindrome | 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'
# Test Case 4:
num4 = '999977755533211'
assert candidate(num4) == 'not possible' |
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.
Maze is n*n matrix and starting point is (0,0) and destination is (n-1,n-1). I can move either right or down.
In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination.
Take input from the user for n and the maze matrix and print the path from source to destination.
Example:
Input: 4,[[1,0,0,0],[1,1,0,1],[0,1,0,1],[1,1,1,1]]
Output: [[1,0,0,0],[1,1,0,0],[0,1,0,0],[0,1,1,1]]"""
| 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 as part of the solution path
solution[x][y] = 1
# Move Right
if solve_maze(maze, x + 1, y, solution, n):
return True
# Move Down
if solve_maze(maze, x, y + 1, solution, n):
return True
# If neither move right nor move down works, backtrack
solution[x][y] = 0
return False
return False
def path(n: int, maze: List[List[int]]) -> List[List[int]]:
# Initialize solution matrix with 0s
solution = [[0 for _ in range(n)] for _ in range(n)]
if not solve_maze(maze, 0, 0, solution, n):
return "No path exists"
return solution | 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(n2, maze2) == [[1, 0, 0], [1, 1, 1], [0, 0, 1]]
n3 = 5
maze3 = [[1, 0, 0, 0, 0], [1, 1, 1, 0, 1], [0, 1, 0, 1, 1], [1, 1, 1, 1, 1], [0, 0, 0, 1, 1]]
assert candidate(n3, maze3) == [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [1, 1, 1, 1, 0], [0, 0, 0, 1, 1]]
n4 = 2
maze4 = [[1, 1], [0, 1]]
assert candidate(n4, maze4) == [[1, 1], [0, 1]] |
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 a number and value X as input from the user. and print the maximum value of the number after swapping the digits at most X times.
Example 1:
Input: '1234567', 4
Output: '7654321'
Input: '3435335', 3
Output: '5543333'"""
| 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]:
max_digit_index = j
# If the maximum digit is different from the current digit, perform the swap
if max_digit_index != i:
num_list[i], num_list[max_digit_index] = num_list[max_digit_index], num_list[i]
swaps -= 1
i += 1
# Convert the list back to a string
result = ''.join(num_list)
return result | 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.
Here coloring of a graph means the assignment of colors to all vertices.
Print 1 if it is possible to color vertices and 0 otherwise.
Take input from the user for n i.e vertices , m i.e colors and e i.e edges and return 1 if it is possible to color vertices and 0 otherwise.
Example 1:
Input: 4,3,5,[[0,1],[1,2],[1,3],[2,3],[3,0],[0,2]]
Output: 1"""
| 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 candidate(6, 2, 7, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0], [0, 3]]) == 1 |
|
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 subsequent number in the sequence must be the sum of the preceding two.
Take a number as input from the user and print 'It is an additive number' if it is additive else print 'It is not an additive number'.
Example:
Input: '112358'
Output: 'It is an additive number'
Input: '199100199'
Output: 'It is an additive number'"""
| 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)
for i in range(1, n // 2 + 1):
for j in range(i + 1, n):
num1, num2 = num[:i], num[i:j]
if (len(num1) > 1 and num1[0] == '0') or (len(num2) > 1 and num2[0] == '0'):
continue
if is_additive(num[j:], num1, num2):
return "It is an additive number"
return "It is not an additive number" | 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 number' |
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 two characters can map to the same digit.
3. Each words[i] and result are decoded as one number without leading zeros.
4. Sum of numbers on the left side (words) will equal to the number on the right side (result).
Take input from the user and check if the equation is solvable or not.
Example 1:
Input: ['send', 'more'], 'money' # Here send and more are words and money is result.
Output: True
Input: ['ox', 'ox'], 'xx' # Here ox and ox are words and xx is result.
Output: False"""
| 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(int("".join(char_to_digit[char] for char in word)) for word in left)
right_sum = int("".join(char_to_digit[char] for char in right))
return left_sum == right_sum
char = list(unique_chars)[index]
for digit in range(10):
if str(digit) not in digits_taken and not (digit == 0 and any(word[0] == char for word in left + [right])):
char_to_digit[char] = str(digit)
digits_taken.add(str(digit))
if solve(index + 1):
return True
del char_to_digit[char]
digits_taken.remove(str(digit))
return False
return solve(0) | 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 of s that is nice. If there are multiple, return the substring of the earliest occurrence.
If there are none, return an 'Not good'.
Example:
Input: 'uSaisAI'
Output: 'SaisAI'
Input: 'xYz'
Output: 'Not good'"""
| 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 is_nice(substring) and len(substring) > len(longest_nice_substr):
longest_nice_substr = substring
return longest_nice_substr if longest_nice_substr else "Not good" | 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 pow(a,b) % 1337.
Example:
Input: 2, [3]
Output: 8
Input: 2, [1,0] # Here 2 is a and 10 is b
Output: 1024"""
| 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 == 1:
result = (result * base) % MOD
return result
b_int = int("".join(map(str, b))) # Convert list to integer
return pow_helper(a, b_int) | 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
Input: [9, -4, 9]
Output: 18"""
| 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: List[int]) -> int:
max_kadane = kadane(arr) # Maximum subarray sum in non-circular fashion
# Invert the array and apply Kadane's algorithm to find the minimum subarray sum
max_wrap = 0
for i in range(len(arr)):
max_wrap += arr[i] # Calculate array-sum
arr[i] = -arr[i] # Invert the array elements
# Max sum with corner elements will be: array-sum - (-max subarray sum of inverted array)
max_wrap = max_wrap + kadane(arr)
# The maximum circular sum will be maximum of two sums
if max_wrap > max_kadane and max_wrap != 0:
return max_wrap
else:
return max_kadane | 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 forgotten list and subset sums, and return the forgotten list.
Example:
Input: 3 ,[ -3,-2,-1,0,0,1,2,3]
Output: [1,2,-3]
Input: 2, [0,0,0,0]
Output: [0,0]"""
| 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 of the elements in 'being' between indices i and j inclusive, where i <= j.
Take input from the user for 'being' and lower and upper and return the number of being-sums that lie in [lower, upper] inclusive.
Example:
Input: [-2, 5, -1], -2, 2
Output: 3"""
| 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 through all pairs (i, j) and calculate range sums S(i, j)
for i in range(n):
for j in range(i, n):
range_sum = prefix_sums[j + 1] - prefix_sums[i]
if lower <= range_sum <= upper:
count += 1
return count | 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
Output: 3"""
| 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] = dp[i - 1][j - 1] + dp[i - 1][j]
return dp[n][r] | 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 that if a ball is dropped from a height greater than T, it will burst, otherwise it will bounce.
There are a few other conditions:
1. If the ball survives the fall, it can be used again.
2. If the ball bursts, it cannot be used again.
3. If the ball survives the fall from a certain height, it will also survive the fall from any height below that.
4. If the ball does not survive the fall from a certain height, it will also not survive the fall from any height above that.
5. All balls are identical and are of the same weight.
Find the minimum number of balls required to find the threshold T.
Take input for the number of balls N and height H from the user and return the minimum number of balls required to find the threshold T.
Example:
Input: 2, 10 # Here 2 is N and 10 is H
Output: 4
Input: 1, 2 # Here 1 is N and 2 is H
Output: 2"""
| 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):
res = 1 + max(ballFloor[i - 1][x - 1], ballFloor[i][j - x])
if res < ballFloor[i][j]:
ballFloor[i][j] = res
return ballFloor[n][k] | 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 stripes at a time. But I can't step on the same stripe twice.
Tell the number of ways I can cross the zebra crossing.
Use dynamic programming to solve this problem.
Take input for the number of stripes in the zebra crossing from the user and return the number of ways to cross the zebra crossing.
Example:
Input: 4
Output: 5
Input: 10
Output: 89"""
| 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
return (dp[n] % 1000000007)
dp = [-1] * (n + 1)
return f(n, dp) | 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 string 'number.'
The result should be returned modulo 10^9 + 7, as the answer might be large.
Take input as a string and return the number of possible ways to write down the string modulo 10^9 + 7.
Example 1:
Input: '327'
Output: 2
Input: '094'
Output: 0"""
| 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:
substr = number[i - length:i]
if (substr[0] != '0' or length == 1) and (i - length == 0 or substr >= number[max(i - 2 * length, 0):i - length]):
# Check if substr is valid and non-decreasing
dp[i] = (dp[i] + dp[i - length]) % MOD
return dp[n] | 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 exactly a positions forward (to the right).
I can jump exactly b positions backward (to the left).
I cannot jump backward twice in a row.
I cannot jump to any forbidden positions.
The forbidden positions are given in the array 'forbidden.' If forbidden[i] is true, it means I cannot jump to position forbidden[i]. The integers a, b, and x are provided.
My goal is to find the minimum number of jumps needed to reach my treasure at position x. If there's no possible sequence of jumps that lands me on position x, the result is -1.
Take input as a, b, x, forbidden from user and return the minimum number of jumps needed to reach my treasure at position x. If there's no possible sequence of jumps that lands
me on position x, the result is -1.
Example 1:
Input: 15, 13, 11, [8,3,16,6,12,20] # a, b, x, forbidden
Output: -1
Input: 16, 9, 7, [1,6,2,14,5,17,4] # a, b, x, forbidden
Output: 2
"""
| 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.popleft()
if position == x:
return steps % MOD
# Forward move
forward_pos = position + a
if forward_pos not in forbidden and (forward_pos, False) not in visited:
visited.add((forward_pos, False))
queue.append((forward_pos, steps + 1, False))
# Backward move, ensuring not to move backward twice in a row
if not last_backward and position - b not in forbidden and position - b >= 0:
backward_pos = position - b
if (backward_pos, True) not in visited:
visited.add((backward_pos, True))
queue.append((backward_pos, steps + 1, True))
return -1 # Treasure is unreachable | 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 point. I want to distribute some items to all houses.
But in such fashion that first i visit to first house, than i visit to all second houses which can be reached from first house,
than i visit to all third houses which can be reached from second house and so on.
Take input from user in form of number of houses and connections between houses and return the order in which i should visit houses.
Starting point is always house 0. and later all houses are numbered in order of their appearance in input.
Example:
Input: 5, [[1,2,3],[],[4],[],[]]
Output: [0,1,2,3,4]
Input: 3, [[1,2],[],[]]
Output: [0,1,2]"""
| 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 houses
for connected_house in connections[house]:
if not visited[connected_house]:
queue.append(connected_house)
return order | 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], [3], [], []]) == [0, 1, 2, 3] |
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 and i have a knight at position (x1,y1) and i want to reach to (x2,y2).
how many minimum steps it would take to reach from (x1,y1) to (x2,y2).
Take input from user for size of board and position of knight and position of destination. and return minimum steps.
Example:
Input: 6, [4,5], [1,1] # 6 is size of board, [4,5] is position of knight and [1,1] is position of destination.
Output: 3 """
| 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 = queue.popleft()
if (row, col) == dist: return step
for drow, dcol in deltas:
row_delta = drow + row
col_delta = dcol + col
row_inbound = 0 <= row_delta < N
col_inbound = 0 <= col_delta < N
if not row_inbound or not col_inbound: continue
if (row_delta, col_delta) not in visited:
queue.append((row_delta, col_delta, step + 1))
visited.add((row_delta, col_delta))
return -1 | 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 complete setup as one chunk.
I want to find all that pole by removal of that just one pole, whole chunk will be disconnected.
There can be multiple such poles which can be removed to disconnect the chunk. list all those poles.
Take input from user for number of poles , wires and path of each wire and return list of poles which can be removed to disconnect the chunk.
Few things to note:
pole number starts from 0 to v-1 and wires are bidirectional.
Example:
Input: 5, 5, [[0,1],[1,4],[4,2],[2,3],[3,4]]
Output: [1,4]
Input: 5, 4, [[0,1],[1,4],[4,2],[2,3]]
Output: [1,4,2]"""
| 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, low, parent, ap, graph, time)
low[u] = min(low[u], low[neighbour])
if parent[u] == -1 and children > 1:
ap[u] = True
if parent[u] != -1 and low[neighbour] >= disc[u]:
ap[u] = True
elif neighbour != parent[u]:
low[u] = min(low[u], disc[neighbour])
def remove_poles(v: int, w: int, wires: List[List[int]]) -> List[int]:
graph = [[] for _ in range(v)]
for wire in wires:
graph[wire[0]].append(wire[1])
graph[wire[1]].append(wire[0])
visited = [False] * v
disc = [float('inf')] * v
low = [float('inf')] * v
parent = [-1] * v
ap = [False] * v # Articulation points
time = [0]
for i in range(v):
if not visited[i]:
dfs(v, i, visited, disc, low, parent, ap, graph, time)
return [i for i, x in enumerate(ap) if x] | 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 stations.
Your task is to find the members of strongly connected stations in the state.
Take input for S , T and T lines of input for tracks. and return the all strongly connected stations.
Assume each station starts with 0 and ends with S-1 and each track if directed from one station to another.
Example:
Input: 5, 5, [[1,0],[0,2],[2,1],[0,3],[3,4]]
Output: [[0,1,2] ,[3] ,[4]]"""
| 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
def dfsUtil(graph, v, visited, component):
visited[v] = True
component.append(v)
for i in graph[v]:
if not visited[i]:
dfsUtil(graph, i, visited, component)
def strongly_connected(S, T, tracks):
graph = [[] for _ in range(S)]
for track in tracks:
graph[track[0]].append(track[1])
stack = []
visited = [False] * S
# Step 1: Fill the stack with vertices based on their finishing times
for i in range(S):
if not visited[i]:
dfs(graph, i, visited, stack)
# Step 2: Transpose the graph
graphT = transpose(graph, S)
# Step 3: Perform DFS on the transposed graph in the order given by the stack
visited = [False] * S
scc = []
while stack:
v = stack.pop()
if not visited[v]:
component = []
dfsUtil(graphT, v, visited, component)
scc.append(sorted(component))
return scc | 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],[6,5],[7,4],[7,6],[8,6],[8,7],[8,8]]) == [[0,1,2],[3,4],[5,6,7],[8]] |
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 description of cells is as follows:
A value of cell S means start.
A value of cell D means end.
A value of cell X means Blank cell.
A value of cell 0 means Wall.
Take input from user for rows and columns of maze and then take input for maze.
Return True if you can reach from start to end else return False.
Example:
Input: 5, 5, [[X,0,X,0,0],[X,0,0,0,X],[X,X,X,X,X],[0,D,X,0,0],[X,0,0,S,X]]
Output: False"""
| 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 all four directions from the current cell
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for di, dj in directions:
if dfs(maze, i + di, j + dj, visited):
return True
return False
def maze(n, m, maze):
visited = [[False for _ in range(m)] for _ in range(n)]
# Find the starting point
for i in range(n):
for j in range(m):
if maze[i][j] == 'S':
return dfs(maze, i, j, visited)
return False # Start point not found | 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'],
['X', '0', '0', 'S', 'X']]) == False
assert candidate(4, 5, [['X', '0', 'X', '0', 'X'],
['0', '0', 'X', '0', 'X'],
['X', 'X', 'X', 'X', 'X'],
['X', 'D', 'X', 'S', 'X']]) == True
assert candidate(3, 3, [['S', '0', '0'],
['0', 'X', 'D'],
['X', '0', '0']]) == False
assert candidate(4, 4, [['S', 'X', '0', 'X'],
['0', 'X', '0', '0'],
['X', 'X', '0', 'D'],
['X', 'X', 'X', 'X']]) == True |
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 :
1. Take input for 2 students at a time and put them in same room.
2. Or give input for 2 students and check if they are in same room or not.
Take input from user for queries he want to perform, queries can be of two types:
1. Add student to room
2. Check if two students are in same room
3. Exit
Example: [query, student1, student2]
Input: [[1,1,3], [2,1,4], [1,2,3], [2,1,3], [3]] # 1 means add student to room, 2 means check if two students are in same room, 3 means exit
Output: [False, True]"""
| 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]]) -> List[bool]:
parent = {} # To keep track of the representative (leader) of each room
output = []
for q in query:
if q[0] == 1: # Add student to room
a, b = q[1], q[2]
if a not in parent:
parent[a] = a
if b not in parent:
parent[b] = b
union(parent, a, b)
elif q[0] == 2: # Check if two students are in the same room
a, b = q[1], q[2]
if a in parent and b in parent and find(parent, a) == find(parent, b):
output.append(True)
else:
output.append(False)
elif q[0] == 3: # Exit
break
return output | 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, 3], [2, 1, 3], [3]]) == [False, True]
assert candidate([[1, 1, 2], [1, 2, 3], [2, 3, 4], [2, 1, 4], [3]]) == [False, False] |
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 the cycles in the system to avoid water wastage.
Take input from user for W water tanks and P pipes. Then take input for each pipe in the format (tank1, tank2).
Return True if there's any cycle in the system else return False.
Few points to note:
1. Each tank have number from 0 to W-1.
2. Try to use disjoint set data structure to solve this problem.
Example:
Input: 5, [[1,3],[3,0],[0,2],[2,4],[4,0]]
Output: True"""
| 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
return False
def water_pipeline(tanks: int, pipes: List[List[int]]) -> bool:
parent = list(range(tanks)) # Each tank is initially its own parent
for a, b in pipes:
if union(parent, a, b): # If union returns True, a cycle is found
return True
return False # No cycles found | 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], [3, 4], [4, 5]]) == False |
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 cost to connect village X and Y with water pipes is C.
Your task is to provide water to each and every village either by building a well in the village or connecting
it to some other village having water. Find the minimum cost to do so.
Take input from user for N, wells[] and pipes[][]. and return the minimum cost to provide water to all villages.
Example 1:
Input: 3, [1, 2, 2], [[1, 2, 1], [2, 3, 1]] # 3 is the number of villages, [1, 2, 2] is the cost of wells in each village,
[[1, 2, 1], [2, 3, 1]] is the cost of connecting pipes in each village
Output: 3"""
| 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]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def water_supply(villages: int, wells: List[int], pipes: List[List[int]]) -> int:
parent = [i for i in range(villages + 1)] # Including the virtual node
rank = [0] * (villages + 1)
# Create edges list: (cost, village1, village2), including virtual node connections
edges = [(cost, 0, i + 1) for i, cost in enumerate(wells)] # Connecting villages to the virtual node (0) via wells
for x, y, c in pipes:
edges.append((c, x, y))
edges.sort() # Sort by cost
total_cost = 0
for cost, x, y in edges:
if find(parent, x) != find(parent, y): # If adding this edge doesn't form a cycle
union(parent, rank, x, y)
total_cost += cost
return total_cost | 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
assert candidate(3, [3, 5, 2], [[1, 2, 1], [2, 3, 2]]) == 5 |
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.
The task is to find the maximum number of student belonging to an gang if it is
possible to distribute all the student among A and B, otherwise print -1.
Take input from user in the form of 2D list and return the maximum number of student belonging to an gang.
Example 1:
Input: [[1,2],[2,3],[2,4],[2,5]]
Output: 4
Example 2:
Input: [[1,2],[2,3],[3,1]]
Output: -1 """
| 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
queue.append(v)
elif color[v] == color[u]: # If the adjacent has the same color, it's not bipartite
return False
return True
def gang_fight(fights: List[List[int]]) -> int:
if not fights:
return 0
# Find the maximum student number to determine the graph size
max_student = max(max(fight) for fight in fights)
graph = [[] for _ in range(max_student + 1)]
color = [-1] * (max_student + 1) # -1 indicates not colored
# Build the graph
for fight in fights:
graph[fight[0]].append(fight[1])
graph[fight[1]].append(fight[0])
# Check if the graph is bipartite and color the graph
for student in range(1, max_student + 1):
if color[student] == -1 and not is_bipartite(graph, student, color):
return -1 # The graph is not bipartite
# Count the number of students in one of the gangs
max_gang_size = color.count(1)
return max(max_gang_size, len(color) - max_gang_size - 1) # Exclude the -1 (not colored) count | 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 possible between the size any two chunck of the colony. If there is only one chunk simply print 0.
chunck is a set of houses connected with each other.
Take input from user foor H and P and then take input for P pipe connections. and return the minimum difference.
example:
Input: 2, 1, [[1,2]] # 2 is the number of houses, 1 is the number of pipes, [[1,2]] is the pipe connection
Output: 0
Input: 4, 2, [[1,2],[2,4]] # 4 is the number of houses, 2 is the number of pipes, [[1,2],[2,4]] is the pipe connection
Output: 2"""
| 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 villages and then to the city.
Now a days there's complain about lack of water in the city. I need to check what is amout of water supplied to the city.
Points to be noted:
1. there may be multiple villages in between water plant and city.
2. villages are interconceted with each other (not all) with pipes.
3. Names of villages are 1 to n.
Take input from user in form of matrix. where first row is for water plant and last row is for city.
in between rows are for villages. If there is no connection between two villages then put 0 in matrix.
If there is connection between two villages then put the rate of water flow in matrix.
Return the amount of water supplied to the city. Try to use max flow concept.
Example:
Input: 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]]
Output: 23"""
| 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:
parent[ind] = u
return True
queue.append(ind)
parent[ind] = u
visited[ind] = True
return False
def edmonds_karp(graph, source, sink):
rGraph = [row[:] for row in graph] # Residual graph
parent = [-1] * len(graph)
max_flow = 0
while bfs(rGraph, source, sink, parent):
path_flow = float('inf')
s = sink
while(s != source):
path_flow = min(path_flow, rGraph[parent[s]][s])
s = parent[s]
max_flow += path_flow
v = sink
while(v != source):
u = parent[v]
rGraph[u][v] -= path_flow
rGraph[v][u] += path_flow
v = parent[v]
return max_flow
def water_plant(cities, connections):
# The source is the water plant (0) and the sink is the city (cities - 1)
return edmonds_karp(connections, 0, cities - 1) | 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 maximum number of truck can be present on a road at a time
From city A to city B given the capacity of each road in terms of number of trucks that can be present on a road at a time.
There can be multiple other cities in between city A and city B.
Roads can be bidirectional.
Take input from user for the number of cities in between city A and city B and the
Matrix of the capacity of the road between each city. and return the maximum number of trucks that can be present on the road at a time.
Example:
Input: 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]]
Output: 10""" | 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 taken between each city.
3. The route is undirected.
Take input from user for number of cities in between home and college; the days taken between each city if there's a route between them.
take input in form of matrix. and return minimum days taken to reach college.
Example:
input: 2, [[0,3,2,0],[0,0,5,2],[0,0,0,3],[0,0,0,0]]
output: 5""" | 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 user as number of organ and capacity of each blood vessel fron organ to organ.
Do this in form of matrix and return max amount of blood that can flow from one organ A to organ B.
Also blood can flow is unidirectional.
Example:
Input: 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]]
Output: 7 """ | 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, there are n routers connected via network links with specific capacities.
Data transfer is unidirectional.
Example:
Input: 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]
Output: 7 # The maximum amount of data that can flow from Computer A to Computer B is 7.""" | 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 divides 100 by a number.
Take input from user for any number and return the result of 100 divided by that number.
Try to use decorator and closure to solve this problem.
Example:
Input: 10
Output: "100 divided by 10 is 10.00"
Input: 3
Output: "100 divided by 3 is 33.33"
"""
| 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 = divide_100_by(user_input)
print(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
output_3 = candidate(user_input_3)
assert output_3 == '100 divided by 7 is 14.29'
user_input_4 = 11
output_4 = candidate(user_input_4)
assert output_4 == '100 divided by 11 is 9.09' |
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 problem.
I want to see how much time each function takes to run.
But I don't want to write a code to calculate the time for each function. show time in nanoseconds.
I want to create one function for that and use it for all the functions.
Try to use concept of decorators and closures to solve this problem.
Take input from user for a and b and return the result of multiplication, division, and power of a and b; along with the time taken to run each function.
In time is greater than 0 return true else return false.
Example:
Input: 10, 5
Output: [["50", "True"], ["2", "True"], ["100000", "True"]]
"""
| 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 elapsed time
return [str(result), str(elapsed > 0)] # Format result and time check
return wrapper
@time_decorator
def multiply(a, b):
result = 0
for _ in range(b):
result += a
return result
@time_decorator
def divide(a, b):
count = 0
while a >= b:
a -= b
count += 1
return count
@time_decorator
def power(a, b):
result = 1
for _ in range(b):
result *= a
return result
def math_ops(a: int, b: int) -> List[List[str]]:
return [multiply(a, b), divide(a, b), power(a, b)] | 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']]
assert candidate(7, -1) == [['21', 'True'], ['2', 'True'], ['343', '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 and print them in sorted order along with the new prefix
'Hind'. If there is a prefix already present then remove it and add 'Hind'.
If there is no prefix then add 'Hind' in front of the number plate.
Try to use decorator and closure concept.
Example:
Input: 5, ['HS 01 1234', '06 1234', 'AB 01 1134', '01 1234', 'XX 11 1234']
Output: ['Hind 01 1134', 'Hind 01 1234', 'Hind 01 1234', 'Hind 06 1234', 'Hind 11 1234']"""
| 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 ["HS", "AB", "XX"] else "Hind " + plate for plate in number]
# Sort the processed number plates
sorted_plates = sorted(processed)
# Return the sorted number plates through the original function
return func(sorted_plates)
return wrapper
@number_plate_decorator
def number_plate(number: List[str]) -> List[str]:
return number | 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 5678", "YY 11 9876"]) == ['Hind 03 5678', 'Hind 05 4321', 'Hind 09 8765', 'Hind 11 9876', 'Hind 12 3456']
assert candidate(["XX 01 2345", "AB 05 6789", "HS 10 4321", "07 9876", "YY 15 8765"]) == ['Hind 01 2345', 'Hind 05 6789', 'Hind 07 9876', 'Hind 10 4321', 'Hind 15 8765']
assert candidate(["YY 21 3456", "HS 18 8765", "AB 09 4321", "15 9876", "XX 13 8765"]) == ['Hind 09 4321', 'Hind 13 8765', 'Hind 15 9876', 'Hind 18 8765', 'Hind 21 3456'] |
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 based on age. The output should list the names of the
youngest individuals first, and for individuals of the same age, maintain the order of their input.
Take input from the user for the number of individuals, and then for each individual.
Example:
Input: 3, [['amit', 'yadav', 23, 'm'], ['amit', 'jain', 12, 'm'], ['ankita', 'did', 23, 'f']]
Output: ['Mr. amit jain', 'Mr. amit yadav', 'Ms. ankita did']"""
| 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 in processed_list]
return func(formatted_list)
return wrapper
@name_directory_decorator
def introduction(name: List[str]) -> List[str]:
return name | 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'], ['alice', 'jones', 25, 'f']]) == ['Ms. jane smith', 'Ms. alice jones', 'Mr. john doe']
assert candidate([['bob', 'brown', 22, 'm'], ['emma', 'white', 22, 'f'], ['david', 'lee', 22, 'm']]) == ['Mr. bob brown', 'Ms. emma white', 'Mr. david lee']
assert candidate([['sam', 'johnson', 18, 'm'], ['sarah', 'miller', 17, 'f'], ['mark', 'anderson', 19, 'm']]) == ['Ms. sarah miller', 'Mr. sam johnson', 'Mr. mark anderson'] |
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 solve this problem.
Take input from the user of n * m matrix and print the minimum sum of the integers along the path.
Example:
Input: 3,3,[[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Input: 2,3,[[1,2,3],[4,5,6]]
Output: 12"""
| 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 i == 0 and j == 0: # Skip the top-left corner
continue
elif i == 0: # Top row, can only come from the left
matrix[i][j] += matrix[i][j-1]
elif j == 0: # Leftmost column, can only come from above
matrix[i][j] += matrix[i-1][j]
else: # Interior cell, take the minimum of the top and left cells
matrix[i][j] += min(matrix[i-1][j], matrix[i][j-1])
return matrix[n-1][m-1] # The minimum path sum is in the bottom-right corner | 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], [1, 1, 1]]) == 5 |
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 (inclusive) which are divisible by 3.
Example:
Input: 2, [[1,10],[3,5]] # 3+6+9=18,
Output: 18, 0"""
| 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, b + 1) if x % 3 == 0)
def sum_divisible_by_3(n: int, pairs: List[List[int]]) -> List[int]:
results = []
with concurrent.futures.ThreadPoolExecutor() as executor:
# Submit tasks to the executor for each pair
futures = [executor.submit(sum_divisible_by_3_in_range, pair) for pair in pairs]
for future in concurrent.futures.as_completed(futures):
# Collect the results as they are completed
results.append(future.result())
return results | 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, 18] |
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 this process concurrently and parallely using threads.
Take input from the user for the number of matrices and n for each matrix and return the result.
Example:
Input: 3, [3,4,5]
Output: [[[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]]]
# 3 matrices of size 3x3 and result of multiplication of 3 matrices
"""
| 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]]
]
assert candidate(2, [1, 2]) == [
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
[[2, 3, 4], [5, 6, 7], [8, 9, 10]],
[[36, 42, 48], [81, 96, 111], [126, 150, 174]]
]
assert candidate(1, [0]) == [
[[0, 1, 2], [3, 4, 5], [6, 7, 8]],
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
] |
|
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 multiprocessing module.
Take input from the user for a and b and return time taken by both functions to complete the task in nano seconds.
If time taken is greater than 0 return True else False.
Example:
Input: 2, 1000
Output: [Time taken by concurently_done is True, Time taken by parallel_done is True]"""
| 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']
assert candidate(5, 200) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True']
assert candidate(10, 100) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True'] |
|
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 to reduce overall processing time.
In the end, you should be able to see the total time taken to complete all tasks.
Take input from the user for the number of tasks and their duration and return the total time taken to complete all tasks in seconds if it is greater than 0 return True else False.
example:
Input: 4, [3,5,2,4] # 4 tasks with duration 3,5,2,4
Output: ["Executing Task C...", "Executing Task A...", "Executing Task D...", "Executing Task B...", True]"""
| 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()
results = []
task_names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"][:n] # Generate task names
with concurrent.futures.ThreadPoolExecutor(max_workers=n) as executor:
# Schedule the tasks concurrently
future_to_task = {executor.submit(simulate_task, task, task_names[i]): i for i, task in enumerate(tasks)}
for future in concurrent.futures.as_completed(future_to_task):
task_name = task_names[future_to_task[future]]
try:
result = future.result()
except Exception as exc:
results.append(f"Task {task_name} generated an exception: {exc}")
else:
results.append(result)
total_time = time.time() - start_time
results.append(True if total_time > 0 else False)
return results | 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 B...", True]
assert candidate(5, [1, 2, 3, 4, 5]) == ["Executing Task A...", "Executing Task B...", "Executing Task C...", "Executing Task D...", "Executing Task E...", True]
assert candidate(2, [5, 3]) == ["Executing Task B...", "Executing Task A...", True] |
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 "Not Done". else return "Done".
Example:
Input: 4, [1000000, 500000, 750000, 200000]
Output: ["Performing Task A...", "Performing Task B...", "Performing Task C...", "Performing Task D...", "Done", "Done", "Done", "Done"]"""
| 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_tasks(n: int, tasks: List[int]) -> List[str]:
results = []
with concurrent.futures.ThreadPoolExecutor(max_workers=n) as executor:
# Schedule the tasks concurrently
future_to_task = {executor.submit(perform_task, task): i for i, task in enumerate(tasks)}
for future in concurrent.futures.as_completed(future_to_task):
task_id = future_to_task[future]
try:
result = future.result()
except Exception as exc:
results.append(f"Task {task_id} generated an exception: {exc}")
else:
results.append(f"Performing Task {chr(65 + task_id)}...") # Task A, B, C, etc.
results.append(result)
return results | 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",
"Done"
]
assert candidate(3, [200, 500, 1000]) == [
"Performing Task A...",
"Performing Task B...",
"Performing Task C...",
"Done",
"Done",
"Done"
]
assert candidate(2, [5, 10]) == [
"Performing Task A...",
"Performing Task B...",
"Done",
"Done"
]
assert candidate(1, [3]) == [
"Performing Task A...",
"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 coefficients in decreasing order of powers.
For example, Polynomial([1, -3, 0, 2]) represents the polynomial 1x^3 - 3x^2 + 2.
2. String Representation: Implement a __str__ method that returns a human-readable string representation of the polynomial.
For example, if the polynomial is Polynomial([1, -3, 0, 2]), the __str__ method should return the string "x^3 - 3x^2 + 2".
3. Addition and Subtraction: Implement methods add and subtract that take another Polynomial object as an argument and return a
new Polynomial object representing the sum or difference of the two polynomials, respectively.
Take input from the user for the coefficients of the two polynomials and create two Polynomial objects.
Example:
Input: [[1, -3, 0, 2], [2, 0, 1]] # cofficients of first polynomial, coefficients of second polynomial
Output: ["x^3 - 3x^2 + 2", "2x^2 + 1", "x^3 - x^2 + 3", "x^3 - 5x^2-1"] # first polynomial, second polynomial, sum, difference
Input: [[1, 2, 3], [3, 2, 1]]
Output: ["x^2 + 2x + 3", "3x^2 + 2x + 1", "4x^2 + 4x + 4", "-2x^2 +2"]"""
| 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:
terms.append(str(coeff))
elif power == 1:
terms.append(f"{coeff}x" if coeff != 1 else "x")
else:
terms.append(f"{coeff}x^{power}" if coeff != 1 else f"x^{power}")
return " + ".join(terms).replace("+ -", "- ")
def add(self, other):
max_len = max(len(self.coeffs), len(other.coeffs))
result_coeffs = [0] * max_len
for i in range(max_len):
coeff1 = self.coeffs[-i-1] if i < len(self.coeffs) else 0
coeff2 = other.coeffs[-i-1] if i < len(other.coeffs) else 0
result_coeffs[-i-1] = coeff1 + coeff2
return Polynomial(result_coeffs)
def subtract(self, other):
max_len = max(len(self.coeffs), len(other.coeffs))
result_coeffs = [0] * max_len
for i in range(max_len):
coeff1 = self.coeffs[-i-1] if i < len(self.coeffs) else 0
coeff2 = other.coeffs[-i-1] if i < len(other.coeffs) else 0
result_coeffs[-i-1] = coeff1 - coeff2
return Polynomial(result_coeffs)
def input_for_class1(coffs: List[List[int]]) -> List[str]:
poly1 = Polynomial(coffs[0])
poly2 = Polynomial(coffs[1])
sum_poly = poly1.add(poly2)
diff_poly = poly1.subtract(poly2)
return [str(poly1), str(poly2), str(sum_poly), str(diff_poly)] | 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 candidate([[5, 0, 0, 1], [0, -2, 1]]) == ['5x^3 + 1', '-2x + 1', '5x^3 - 2x^2 + 1', '5x^3 + 2x']
assert candidate([[1, 1, 1, 1], [1, 1, 1]]) == ['x^3 + x^2 + x + 1', 'x^2 + x + 1', 'x^3 + 2x^2 + 2x + 2', 'x^3'] |
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 Person to have only name and id number. And i want to add salary and position to another class named "Employee" which
Does the all the work of printing the information. I want to see how you do it. I want to see how you use inheritance and polymorphism.
Take input from user for name, id number, salary and position and create object of class Employee and print all the information of that object.
Example:
Input: ["John", 1234, 10000, "Manager"]
Output: "My name is John, My id number is 1234, My salary is 10000 and my position is Manager."
Input: ["Ram", 12223, 20000, "CEO"]
Output: "My name is Ram, My id number is 12223, My salary is 20000 and my position is CEO."
""" | 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.position = position
def print_information(self):
return f"My name is {self.name}, My id number is {self.id_number}, My salary is {self.salary} and my position is {self.position}."
# Example usage:
def input_for_class2(entries: List[str]) -> str:
name, id_number, salary, position = entries
employee = Employee(name, int(id_number), int(salary), position)
return employee.print_information() | 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 12223, My salary is 20000 and my position is CEO."
assert candidate(["Alice", "5678", "15000", "Engineer"]) == "My name is Alice, My id number is 5678, My salary is 15000 and my position is Engineer."
assert candidate(["Bob", "9876", "12000", "Developer"]) == "My name is Bob, My id number is 9876, My salary is 12000 and my position is Developer."
|
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, coupe, hatchback, and truck.
1. Sedan class displays " This is a sedan car with 4 doors and 5 seats, usage is for family."
2. SUV class displays " This is a SUV car with 4 doors and 5 seats, usage is for offroad."
3. Coupe class displays " This is a coupe car with 2 doors and 2 seats, usage is for sport."
4. Hatchback class displays " This is a hatchback car with 4 doors and 5 seats, usage is for small family."
5. Truck class displays " This is a truck car with 2 doors and 3 seats, usage is for work."
when user inputs the car type, it will display the description of the of class car and the description of the car type.
Take input from user and display the description of the car type.
Example:
Input: sedan
Output: 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.
Input: suv
Output: Welcome to car catalog, here you can find all the cars you need. This is a SUV car with 4 doors and 5 seats, usage is for offroad."""
| 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 doors and 5 seats, usage is for family."
class SUV(Car):
def __init__(self):
super().__init__()
self.description += " This is a SUV car with 4 doors and 5 seats, usage is for offroad."
class Coupe(Car):
def __init__(self):
super().__init__()
self.description += " This is a coupe car with 2 doors and 2 seats, usage is for sport."
class Hatchback(Car):
def __init__(self):
super().__init__()
self.description += " This is a hatchback car with 4 doors and 5 seats, usage is for small family."
class Truck(Car):
def __init__(self):
super().__init__()
self.description += " This is a truck car with 2 doors and 3 seats, usage is for work."
# Example usage:
def input_for_class3(typess: str) -> str:
car_types = {
'sedan': Sedan(),
'suv': SUV(),
'coupe': Coupe(),
'hatchback': Hatchback(),
'truck': Truck(),
}
if typess.lower() in car_types:
return car_types[typess.lower()].get_description()
else:
return "Invalid car type. Please choose from sedan, suv, coupe, hatchback, or truck." | 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 find all the cars you need. This is a SUV car with 4 doors and 5 seats, usage is for offroad."
assert candidate("coupe") == "Welcome to car catalog, here you can find all the cars you need. This is a coupe car with 2 doors and 2 seats, usage is for sport."
assert candidate("hatchback") == "Welcome to car catalog, here you can find all the cars you need. This is a hatchback car with 4 doors and 5 seats, usage is for small family."
assert candidate("truck") == "Welcome to car catalog, here you can find all the cars you need. This is a truck car with 2 doors and 3 seats, usage is for work."
|
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 initial balance.
2. Deposit and Withdrawal: Implement methods deposit and withdraw that allow the account holder to deposit and withdraw funds, respectively.
Ensure that withdrawals do not exceed the available balance. # "Withdrawal amount exceeds available balance."
3. Balance Inquiry: Implement a method get_balance that returns the current balance.
Take input from the user for the account holder's name and initial balance. later, take input from the user for the amount to deposit, withdraw, or check balance.
Example
Input: ["John", 1000, "Deposit", 500, "Withdraw", 200, "Balance", "Exit" ]
Output: ["Your current balance is 1300"]""" | 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:
return "Withdrawal amount exceeds available balance."
self.balance -= amount
def get_balance(self):
return self.balance
def input_for_class4(data: List[str]) -> List[str]:
account = BankAccount(data[0], float(data[1]))
i = 2 # Start from the third item in the list, which is the first operation
output = []
while i < len(data):
operation = data[i]
if operation == "Deposit":
i += 1
account.deposit(float(data[i]))
elif operation == "Withdraw":
i += 1
withdrawal_message = account.withdraw(float(data[i]))
if withdrawal_message:
output.append(withdrawal_message)
elif operation == "Balance":
output.append(f"Your current balance is {account.get_balance()}")
elif operation == "Exit":
break
i += 1
return output | 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"]
assert candidate(["Bob", "500", "Withdraw", "700", "Deposit", "200", "Balance", "Exit"]) == ["Withdrawal amount exceeds available balance.", "Your current balance is 700"]
assert candidate(["Eve", "2000", "Withdraw", "500", "Deposit", "1000", "Balance", "Exit"]) == ["Your current balance is 2500"]
|
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:
Initialization: The class should be initialized with the construction site's name and the initial budget.
Material Inventory: Implement methods to add materials to the construction site's inventory and retrieve the current inventory status.
Worker Management: Implement methods to add and remove workers from the construction site. Each worker has a unique identifier, and name.
Budget Tracking: Implement methods to track expenses and remaining budget. Ensure that expenses are deducted from the budget
when materials are purchased or workers are hired.
Progress Monitoring: Implement a method to monitor the overall progress of the construction site based on completed tasks and remaining tasks.
Take apporpriate input from the user to test your class. You may use the following sample input/output to test your class:
Example:
Input: ["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, "status update", "completed", "EXIT"]
Output: [Construction site name is IIT, budget is 100000, material inventory is {'cement': 100, 'bricks': 1000, 'sand': 500}, workers are {1: 'John', 2: 'Mike', 3: 'Mary'}]""" | 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_inventory:
self.material_inventory[material_name] += quantity
else:
self.material_inventory[material_name] = quantity
def get_material_inventory(self):
return self.material_inventory
def add_worker(self, worker_name: str, worker_id: int):
self.workers[worker_id] = worker_name
def remove_worker(self, worker_id: int):
if worker_id in self.workers:
del self.workers[worker_id]
def get_workers(self):
return self.workers
def track_expense(self, expense: float):
self.budget -= expense
def get_budget(self):
return self.budget
def monitor_progress(self, status: str):
if status.lower() == "completed":
return f"Construction site {self.name} has been completed."
elif status.lower() == "in progress":
return f"Construction site {self.name} is still in progress."
else:
return "Invalid progress status."
# Example usage:
def input_for_class5(data: List[str]) -> List[str]:
construction_site_name = data[0]
initial_budget = float(data[1])
construction_site = ConstructionSite(construction_site_name, initial_budget)
results = []
i = 2
while i < len(data):
action = data[i]
if action.lower() == "material addition":
material_name = data[i + 1]
quantity = int(data[i + 2])
construction_site.add_material(material_name, quantity)
i += 3
elif action.lower() == "worker addition":
worker_name = data[i + 1]
worker_id = int(data[i + 2])
construction_site.add_worker(worker_name, worker_id)
i += 3
elif action.lower() == "worker removal":
worker_id = int(data[i + 1])
construction_site.remove_worker(worker_id)
i += 2
elif action.lower() == "status update":
status = data[i + 1]
progress = construction_site.monitor_progress(status)
results.append(progress)
i += 2
elif action.lower() == "exit":
break
results.append(f"Construction site name is {construction_site.name}, budget is {construction_site.budget}, material inventory is {construction_site.get_material_inventory()}, workers are {construction_site.get_workers()}")
return results | 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', 'status update', 'completed', 'EXIT']) == ['Construction site name is IIT, budget is 99900.0, material inventory is {'cement': 100, 'bricks': 1000, 'sand': 500}, workers are {1: 'John', 2: 'Mike', 3: 'Mary'}']
assert candidate(['TechPark', '50000', 'material addition', 'steel', '200', 'material addition', 'concrete', '300', 'worker addition', 'Alice', '1', 'status update', 'in progress', 'EXIT']) == ['Construction site name is TechPark, budget is 50000.0, material inventory is {'steel': 200, 'concrete': 300}, workers are {1: 'Alice'}']
assert candidate(['HomeProject', '200000', 'material addition', 'wood', '150', 'material addition', 'tiles', '400', 'worker addition', 'Bob', '1', 'worker addition', 'Charlie', '2', 'status update', 'completed', 'EXIT']) == ['Construction site name is HomeProject, budget is 200000.0, material inventory is {'wood': 150, 'tiles': 400}, workers are {1: 'Bob', 2: 'Charlie'}']
assert candidate(['HospitalBuild', '1000000', 'material addition', 'cement', '500', 'material addition', 'bricks', '1200', 'worker addition', 'David', '1', 'worker removal', '1', 'status update', 'in progress', 'EXIT']) == ['Construction site name is HospitalBuild, budget is 1000000.0, material inventory is {'cement': 500, 'bricks': 1200}, workers are {}'] |
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"
4. When I exit from "with" statement, it should print "exit method called"
5. Before exit from "with" statement, it should print "XXXX" (XXXX - any text from user)
Take XXXX from user and print all 4 messages in order mentioned above.
Example:
Input: "Hello i'm in context manager"
Output: ["init method called", "enter method called", "Hello i'm in context manager", "exit 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 input_for_cont1(data: str) -> List[str]:
messages = []
# Define a function to capture print statements
def mock_print(*args, **kwargs):
messages.append(' '.join(map(str, args)))
# Replace the built-in print function with mock_print within this context
original_print = __builtins__.print
__builtins__.print = mock_print
# Use the ContextManager with the provided data
with ContextManager(data):
pass
# Restore the original print function
__builtins__.print = original_print
return messages | 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 precise upto
n decimal places.
Take input from user for two numbers and precision value n. and return the
result upto n decimal places in form of string.
You should use context manager to set precision value.
Example:
Input: 1, 42, 42 # 1 is a, 42 is b, 42 is precision value
Output: "0.0238095238095238095238095238095238095238095"
""" | 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
n decimal places.
Take input from user for two numbers and precision value n. and return the
result upto n decimal places in form of string.
You should use context manager to set precision value.
Example:
Input: 1, 42, 42 # 1 is a, 42 is b, 42 is precision value
Output: "0.0238095238095238095238095238095238095238095"
""" | 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 them.
The error is: unsupported operand type(s) for //: 'int' and 'str'
The error is: integer division or modulo by zero
Example:
Input: 5,2
Output: "2.5"
Input: 5,0
Output: "The error is: integer division or modulo by zero """
| 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 it.
The error is: I/O operation on closed file."""
| 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 possible.
Take input from user for n and m and return the maximum capacity of scope.
Try to use recursion to solve this problem.
Example:
Input: 3, 5
Output: 1
Input: 4,20
Output: 4
Input: 6,15
Output: 3""" | 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 wall should be completely covered by the stencils.
Take input from user for n, a, b, and c and return the maximum number of stencils used to paint the wall.
Try to use recursion to solve this problem.
Example:
Input: 23, 11, 9, 12
Output: 2
Input: 17, 10, 11, 3
Output: 3""" | 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 left in the circle so that I can win the game.
Take input from user for n and k and return the position of the last chair left in the circle.
Try to use recursion to solve this problem.
Example:
Input: 14, 2
Output: 13
Input: 7, 3
Output: 4""" | 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'},4:{'g','h','i'},5:{'j','k','l'},6:{'m','n','o'},7:{'p','q','r','s'},8:{'t','u','v'},9:{'w','x','y','z'},0:{}
Take input from user for the order of key presses and return the words that can be typed using the given number of key presses.
Try to use recursion to solve this problem.
Example:
Input: [2,3,4]
Output: ['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']""" | 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 in letters]
return ret | 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]) == []
assert candidate([2,3]) == ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf'] |
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 partial).
Take input from user for s and ptr and return True if the pattern matches the string, else False.
Try to use recursion to solve this problem.
Example:
Input: s = "aa", ptr = "a+"
Output: True
Input: s = "aa", ptr = "a"
Output: false
""" | 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(p) and p[j] == '-':
j += 1
return j == len(p) | 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 |
Subsets and Splits