Prompt
stringlengths
16
11.5k
Completions
stringlengths
84
25.3k
Write a function countleftnode returns the number of left children in the tree. For example: the following tree has four left children the nodes storing the values 6, 3, 7, and 10: 9 6 12 3 8 10 15 7 18 countleftnode 4 The tree is created for testing: 9 6 12 3 8 10 15 7 18 countleftnode 4
import unittest from bst import Node from bst import bst def count_left_node(root): if root is None: return 0 elif root.left is None: return count_left_node(root.right) else: return 1 + count_left_node(root.left) + count_left_node(root.right) """ The tree is created for testing: 9 / \ 6 12 / \ / \ 3 8 10 15 / \ 7 18 count_left_node = 4 """ class TestSuite(unittest.TestCase): def setUp(self): self.tree = bst() self.tree.insert(9) self.tree.insert(6) self.tree.insert(12) self.tree.insert(3) self.tree.insert(8) self.tree.insert(10) self.tree.insert(15) self.tree.insert(7) self.tree.insert(18) def test_count_left_node(self): self.assertEqual(4, count_left_node(self.tree.root)) if __name__ == '__main__': unittest.main()
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference possibly updated of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Note: Time complexity should be Oheight of tree. Example: root 5,3,6,2,4,null,7 key 3 5 3 6 2 4 7 Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is 5,4,6,2,null,null,7, shown in the following BST. 5 4 6 2 7 Another valid answer is 5,2,6,null,4,null,7. 5 2 6 4 7 :type root: TreeNode :type key: int :rtype: TreeNode Find the right most leaf of the left subtree Attach right child to the right of that leaf Return left child instead of root, a.k.a delete root If left or right child got deleted, the returned root is the child of the deleted node.
class Solution(object): def delete_node(self, root, key): """ :type root: TreeNode :type key: int :rtype: TreeNode """ if not root: return None if root.val == key: if root.left: # Find the right most leaf of the left sub-tree left_right_most = root.left while left_right_most.right: left_right_most = left_right_most.right # Attach right child to the right of that leaf left_right_most.right = root.right # Return left child instead of root, a.k.a delete root return root.left else: return root.right # If left or right child got deleted, the returned root is the child of the deleted node. elif root.val > key: root.left = self.deleteNode(root.left, key) else: root.right = self.deleteNode(root.right, key) return root
Write a function depthSum returns the sum of the values stored in a binary search tree of integers weighted by the depth of each value. For example: 9 6 12 3 8 10 15 7 18 depthsum 19 2612 3381015 4718 The tree is created for testing: 9 6 12 3 8 10 15 7 18 depthsum 19 2612 3381015 4718
import unittest from bst import Node from bst import bst def depth_sum(root, n): if root: return recur_depth_sum(root, 1) def recur_depth_sum(root, n): if root is None: return 0 elif root.left is None and root.right is None: return root.data * n else: return n * root.data + recur_depth_sum(root.left, n+1) + recur_depth_sum(root.right, n+1) """ The tree is created for testing: 9 / \ 6 12 / \ / \ 3 8 10 15 / \ 7 18 depth_sum = 1*9 + 2*(6+12) + 3*(3+8+10+15) + 4*(7+18) """ class TestSuite(unittest.TestCase): def setUp(self): self.tree = bst() self.tree.insert(9) self.tree.insert(6) self.tree.insert(12) self.tree.insert(3) self.tree.insert(8) self.tree.insert(10) self.tree.insert(15) self.tree.insert(7) self.tree.insert(18) def test_depth_sum(self): self.assertEqual(253, depth_sum(self.tree.root, 4)) if __name__ == '__main__': unittest.main()
Write a function height returns the height of a tree. The height is defined to be the number of levels. The empty tree has height 0, a tree of one node has height 1, a root node with one or two leaves as children has height 2, and so on For example: height of tree is 4 9 6 12 3 8 10 15 7 18 height 4 The tree is created for testing: 9 6 12 3 8 10 15 7 18 countleftnode 4
import unittest from bst import Node from bst import bst def height(root): if root is None: return 0 else: return 1 + max(height(root.left), height(root.right)) """ The tree is created for testing: 9 / \ 6 12 / \ / \ 3 8 10 15 / \ 7 18 count_left_node = 4 """ class TestSuite(unittest.TestCase): def setUp(self): self.tree = bst() self.tree.insert(9) self.tree.insert(6) self.tree.insert(12) self.tree.insert(3) self.tree.insert(8) self.tree.insert(10) self.tree.insert(15) self.tree.insert(7) self.tree.insert(18) def test_height(self): self.assertEqual(4, height(self.tree.root)) if __name__ == '__main__': unittest.main()
Given a binary tree, determine if it is a valid binary search tree BST. Assume a 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. Example 1: 2 1 3 Binary tree 2,1,3, return true. Example 2: 1 2 3 Binary tree 1,2,3, return false. :type root: TreeNode :rtype: bool
def is_bst(root): """ :type root: TreeNode :rtype: bool """ stack = [] pre = None while root or stack: while root: stack.append(root) root = root.left root = stack.pop() if pre and root.val <= pre.val: return False pre = root root = root.right return True
:type root: TreeNode :type k: int :rtype: int
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def kth_smallest(root, k): stack = [] while root or stack: while root: stack.append(root) root = root.left root = stack.pop() k -= 1 if k == 0: break root = root.right return root.val class Solution(object): def kth_smallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ count = [] self.helper(root, count) return count[k-1] def helper(self, node, count): if not node: return self.helper(node.left, count) count.append(node.val) self.helper(node.right, count) if __name__ == '__main__': n1 = Node(100) n2 = Node(50) n3 = Node(150) n4 = Node(25) n5 = Node(75) n6 = Node(125) n7 = Node(175) n1.left, n1.right = n2, n3 n2.left, n2.right = n4, n5 n3.left, n3.right = n6, n7 print(kth_smallest(n1, 2)) print(Solution().kth_smallest(n1, 2))
Given a binary search tree BST, find the lowest common ancestor LCA of two given nodes in the BST. According to the definition of LCA on Wikipedia: The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants where we allow a node to be a descendant of itself. 6 2 8 0 4 7 9 3 5 For example, the lowest common ancestor LCA of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. :type root: Node :type p: Node :type q: Node :rtype: Node
def lowest_common_ancestor(root, p, q): """ :type root: Node :type p: Node :type q: Node :rtype: Node """ while root: if p.val > root.val < q.val: root = root.right elif p.val < root.val > q.val: root = root.left else: return root
Write a function numempty returns returns the number of empty branches in a tree. Function should count the total number of empty branches among the nodes of the tree. A leaf node has two empty branches. In the case, if root is None, it considered as a 1 empty branch For example: the following tree has 10 empty branch is empty branch 9 6 12 3 8 10 15 7 18 emptybranch 10 The tree is created for testing: 9 6 12 3 8 10 15 7 18 numempty 10
import unittest from bst import Node from bst import bst def num_empty(root): if root is None: return 1 elif root.left is None and root.right: return 1 + num_empty(root.right) elif root.right is None and root.left: return 1 + num_empty(root.left) else: return num_empty(root.left) + num_empty(root.right) """ The tree is created for testing: 9 / \ 6 12 / \ / \ 3 8 10 15 / \ 7 18 num_empty = 10 """ class TestSuite(unittest.TestCase): def setUp(self): self.tree = bst() self.tree.insert(9) self.tree.insert(6) self.tree.insert(12) self.tree.insert(3) self.tree.insert(8) self.tree.insert(10) self.tree.insert(15) self.tree.insert(7) self.tree.insert(18) def test_num_empty(self): self.assertEqual(10, num_empty(self.tree.root)) if __name__ == '__main__': unittest.main()
Given n, how many structurally unique BST's binary search trees that store values 1...n? For example, Given n 3, there are a total of 5 unique BST's. 1 3 3 2 1 3 2 1 1 3 2 2 1 2 3 Taking 1n as root respectively: 1 as root: of trees F0 Fn1 F0 1 2 as root: of trees F1 Fn2 3 as root: of trees F2 Fn3 ... n1 as root: of trees Fn2 F1 n as root: of trees Fn1 F0 So, the formulation is: Fn F0 Fn1 F1 Fn2 F2 Fn3 ... Fn2 F1 Fn1 F0 :type n: int :rtype: int
""" Taking 1~n as root respectively: 1 as root: # of trees = F(0) * F(n-1) // F(0) == 1 2 as root: # of trees = F(1) * F(n-2) 3 as root: # of trees = F(2) * F(n-3) ... n-1 as root: # of trees = F(n-2) * F(1) n as root: # of trees = F(n-1) * F(0) So, the formulation is: F(n) = F(0) * F(n-1) + F(1) * F(n-2) + F(2) * F(n-3) + ... + F(n-2) * F(1) + F(n-1) * F(0) """ def num_trees(n): """ :type n: int :rtype: int """ dp = [0] * (n+1) dp[0] = 1 dp[1] = 1 for i in range(2, n+1): for j in range(i+1): dp[i] += dp[i-j] * dp[j-1] return dp[-1]
Given two arrays representing preorder and postorder traversal of a full binary tree, construct the binary tree and print the inorder traversal of the tree. A full binary tree has either 0 or 2 children. Algorithm: 1. Assign the first element of preorder array as root of the tree. 2. Find the same element in the postorder array and divide the postorder array into left and right subtree. 3. Repeat the above steps for all the elements and construct the tree. Eg: pre 1, 2, 4, 8, 9, 5, 3, 6, 7 post 8, 9, 4, 5, 2, 6, 7, 3, 1 Tree: 1 2 3 4 5 6 7 8 9 Output: 8 4 9 2 5 1 6 3 7 Recursive function that constructs tree from preorder and postorder array. preIndex is a global variable that keeps track of the index in preorder array. preorder and postorder array are represented are pre and post respectively. low and high are the indices for the postorder array. Base case If only one element in the subarray return root Find the next element of pre in post Use index of element present in postorder to divide postorder array to two parts: left subtree and right subtree Main Function that will construct the full binary tree from given preorder and postorder array. Prints the tree constructed in inorder format
class TreeNode: def __init__(self, val, left = None, right = None): self.val = val self.left = left self.right = right pre_index = 0 def construct_tree_util(pre: list, post: list, low: int, high: int, size: int): """ Recursive function that constructs tree from preorder and postorder array. preIndex is a global variable that keeps track of the index in preorder array. preorder and postorder array are represented are pre[] and post[] respectively. low and high are the indices for the postorder array. """ global pre_index if pre_index == -1: pre_index = 0 #Base case if(pre_index >= size or low > high): return None root = TreeNode(pre[pre_index]) pre_index += 1 #If only one element in the subarray return root if(low == high or pre_index >= size): return root #Find the next element of pre[] in post[] i = low while i <= high: if(pre[pre_index] == post[i]): break i += 1 #Use index of element present in postorder to divide postorder array #to two parts: left subtree and right subtree if(i <= high): root.left = construct_tree_util(pre, post, low, i, size) root.right = construct_tree_util(pre, post, i+1, high, size) return root def construct_tree(pre: list, post: list, size: int): """ Main Function that will construct the full binary tree from given preorder and postorder array. """ global pre_index root = construct_tree_util(pre, post, 0, size-1, size) return print_inorder(root) def print_inorder(root: TreeNode, result = None): """ Prints the tree constructed in inorder format """ if root is None: return [] if result is None: result = [] print_inorder(root.left, result) result.append(root.val) print_inorder(root.right, result) return result if __name__ == '__main__': pre = [1, 2, 4, 5, 3, 6, 7] post = [4, 5, 2, 6, 7, 3, 1] size = len(pre) result = construct_tree(pre, post, size) print(result)
Given a binary tree, find the deepest node that is the left child of its parent node. Example: 1 2 3 4 5 6 7 should return 4.
# Given a binary tree, find the deepest node # that is the left child of its parent node. # Example: # 1 # / \ # 2 3 # / \ \ # 4 5 6 # \ # 7 # should return 4. from tree.tree import TreeNode class DeepestLeft: def __init__(self): self.depth = 0 self.Node = None def find_deepest_left(root, is_left, depth, res): if not root: return if is_left and depth > res.depth: res.depth = depth res.Node = root find_deepest_left(root.left, True, depth + 1, res) find_deepest_left(root.right, False, depth + 1, res) if __name__ == '__main__': root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.right = TreeNode(6) root.right.right.right = TreeNode(7) res = DeepestLeft() find_deepest_left(root, True, 1, res) if res.Node: print(res.Node.val)
Fenwick Tree Binary Indexed Tree Consider we have an array arr0 . . . n1. We would like to 1. Compute the sum of the first i elements. 2. Modify the value of a specified element of the array arri x where 0 i n1. A simple solution is to run a loop from 0 to i1 and calculate the sum of the elements. To update a value, simply do arri x. The first operation takes On time and the second operation takes O1 time. Another simple solution is to create an extra array and store the sum of the first ith elements at the ith index in this new array. The sum of a given range can now be calculated in O1 time, but the update operation takes On time now. This works well if there are a large number of query operations but a very few number of update operations. There are two solutions that can perform both the query and update operations in Ologn time. 1. Fenwick Tree 2. Segment Tree Compared with Segment Tree, Binary Indexed Tree requires less space and is easier to implement. Returns sum of arr0..index. This function assumes that the array is preprocessed and partial sums of array elements are stored in bittree. index in bittree is 1 more than the index in arr Traverse ancestors of bittreeindex Add current element of bittree to sum Move index to parent node in getSum View Updates a node in Binary Index Tree bittree at given index in bittree. The given value 'val' is added to bittreei and all of its ancestors in tree. index in bitree is 1 more than the index in arr Traverse all ancestors and add 'val' Add 'val' to current node of bittree Update index to that of parent in update View Constructs and returns a Binary Indexed Tree for given array of size n. Create and initialize bitree as 0 Store the actual values in bitree using update
class Fenwick_Tree(object): def __init__(self, freq): self.arr = freq self.n = len(freq) def get_sum(self, bit_tree, i): """ Returns sum of arr[0..index]. This function assumes that the array is preprocessed and partial sums of array elements are stored in bit_tree[]. """ s = 0 # index in bit_tree[] is 1 more than the index in arr[] i = i+1 # Traverse ancestors of bit_tree[index] while i > 0: # Add current element of bit_tree to sum s += bit_tree[i] # Move index to parent node in getSum View i -= i & (-i) return s def update_bit(self, bit_tree, i, v): """ Updates a node in Binary Index Tree (bit_tree) at given index in bit_tree. The given value 'val' is added to bit_tree[i] and all of its ancestors in tree. """ # index in bit_ree[] is 1 more than the index in arr[] i += 1 # Traverse all ancestors and add 'val' while i <= self.n: # Add 'val' to current node of bit_tree bit_tree[i] += v # Update index to that of parent in update View i += i & (-i) def construct(self): """ Constructs and returns a Binary Indexed Tree for given array of size n. """ # Create and initialize bit_ree[] as 0 bit_tree = [0]*(self.n+1) # Store the actual values in bit_ree[] using update() for i in range(self.n): self.update_bit(bit_tree, i, self.arr[i]) return bit_tree
invert a binary tree
# invert a binary tree def reverse(root): if root is None: return root.left, root.right = root.right, root.left if root.left: reverse(root.left) if root.right: reverse(root.right)
ON solution return 0 if unbalanced else depth 1 def isbalancedroot: ON2 solution left maxheightroot.left right maxheightroot.right return absleftright 1 and isbalancedroot.left and isbalancedroot.right def maxheightroot: if root is None: return 0 return maxmaxheightroot.left, maxheightroot.right 1
def is_balanced(root): return __is_balanced_recursive(root) def __is_balanced_recursive(root): """ O(N) solution """ return -1 != __get_depth(root) def __get_depth(root): """ return 0 if unbalanced else depth + 1 """ if root is None: return 0 left = __get_depth(root.left) right = __get_depth(root.right) if abs(left-right) > 1 or -1 in [left, right]: return -1 return 1 + max(left, right) # def is_balanced(root): # """ # O(N^2) solution # """ # left = max_height(root.left) # right = max_height(root.right) # return abs(left-right) <= 1 and is_balanced(root.left) and # is_balanced(root.right) # def max_height(root): # if root is None: # return 0 # return max(max_height(root.left), max_height(root.right)) + 1
Given two binary trees s and t, check if t is a subtree of s. A subtree of a tree t is a tree consisting of a node in t and all of its descendants in t. Example 1: Given s: 3 4 5 1 2 Given t: 4 1 2 Return true, because t is a subtree of s. Example 2: Given s: 3 4 5 1 2 0 Given t: 3 4 1 2 Return false, because even though t is part of s, it does not contain all descendants of t. Follow up: What if one tree is significantly lager than the other?
import collections def is_subtree(big, small): flag = False queue = collections.deque() queue.append(big) while queue: node = queue.popleft() if node.val == small.val: flag = comp(node, small) break else: queue.append(node.left) queue.append(node.right) return flag def comp(p, q): if p is None and q is None: return True if p is not None and q is not None: return p.val == q.val and comp(p.left,q.left) and comp(p.right, q.right) return False
Given a binary tree, check whether it is a mirror of itself ie, symmetric around its center. For example, this binary tree 1,2,2,3,4,4,3 is symmetric: 1 2 2 3 4 4 3 But the following 1,2,2,null,3,null,3 is not: 1 2 2 3 3 Note: Bonus points if you could solve it both recursively and iteratively. TC: Ob SC: Olog n
# TC: O(b) SC: O(log n) def is_symmetric(root): if root is None: return True return helper(root.left, root.right) def helper(p, q): if p is None and q is None: return True if p is not None or q is not None or q.val != p.val: return False return helper(p.left, q.right) and helper(p.right, q.left) def is_symmetric_iterative(root): if root is None: return True stack = [[root.left, root.right]] while stack: left, right = stack.pop() # popleft if left is None and right is None: continue if left is None or right is None: return False if left.val == right.val: stack.append([left.left, right.right]) stack.append([left.right, right.left]) else: return False return True
Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along the parentchild connections. The longest consecutive path need to be from parent to child cannot be the reverse. For example, 1 3 2 4 5 Longest consecutive sequence path is 345, so return 3. 2 3 2 1 :type root: TreeNode :rtype: int
def longest_consecutive(root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 max_len = 0 dfs(root, 0, root.val, max_len) return max_len def dfs(root, cur, target, max_len): if root is None: return if root.val == target: cur += 1 else: cur = 1 max_len = max(cur, max_len) dfs(root.left, cur, root.val+1, max_len) dfs(root.right, cur, root.val+1, max_len)
Given a binary tree, find the lowest common ancestor LCA of two given nodes in the tree. According to the definition of LCA on Wikipedia: The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants where we allow a node to be a descendant of itself. 3 5 1 6 2 0 8 7 4 For example, the lowest common ancestor LCA of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
def lca(root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root is None or root is p or root is q: return root left = lca(root.left, p, q) right = lca(root.right, p, q) if left is not None and right is not None: return root return left if left else right
Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. def maxheightroot: if not root: return 0 return maxmaxDepthroot.left, maxDepthroot.right 1 iterative
# def max_height(root): # if not root: # return 0 # return max(maxDepth(root.left), maxDepth(root.right)) + 1 # iterative from tree import TreeNode def max_height(root): if root is None: return 0 height = 0 queue = [root] while queue: height += 1 level = [] while queue: node = queue.pop(0) if node.left is not None: level.append(node.left) if node.right is not None: level.append(node.right) queue = level return height def print_tree(root): if root is not None: print(root.val) print_tree(root.left) print_tree(root.right) if __name__ == '__main__': tree = TreeNode(10) tree.left = TreeNode(12) tree.right = TreeNode(15) tree.left.left = TreeNode(25) tree.left.left.right = TreeNode(100) tree.left.right = TreeNode(30) tree.right.left = TreeNode(36) height = max_height(tree) print_tree(tree) print("height:", height)
:type root: TreeNode :rtype: int iterative
from tree import TreeNode def min_depth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 if root.left is not None or root.right is not None: return max(self.minDepth(root.left), self.minDepth(root.right))+1 return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 # iterative def min_height(root): if root is None: return 0 height = 0 level = [root] while level: height += 1 new_level = [] for node in level: if node.left is None and node.right is None: return height if node.left is not None: new_level.append(node.left) if node.right is not None: new_level.append(node.right) level = new_level return height def print_tree(root): if root is not None: print(root.val) print_tree(root.left) print_tree(root.right) if __name__ == '__main__': tree = TreeNode(10) tree.left = TreeNode(12) tree.right = TreeNode(15) tree.left.left = TreeNode(25) tree.left.left.right = TreeNode(100) tree.left.right = TreeNode(30) tree.right.left = TreeNode(36) height = min_height(tree) print_tree(tree) print("height:", height)
Given a binary tree and a sum, determine if the tree has a roottoleaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum 22, 5 4 8 11 13 4 7 2 1 return true, as there exist a roottoleaf path 54112 which sum is 22. :type root: TreeNode :type sum: int :rtype: bool DFS with stack BFS with queue
def has_path_sum(root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if root is None: return False if root.left is None and root.right is None and root.val == sum: return True sum -= root.val return has_path_sum(root.left, sum) or has_path_sum(root.right, sum) # DFS with stack def has_path_sum2(root, sum): if root is None: return False stack = [(root, root.val)] while stack: node, val = stack.pop() if node.left is None and node.right is None: if val == sum: return True if node.left is not None: stack.append((node.left, val+node.left.val)) if node.right is not None: stack.append((node.right, val+node.right.val)) return False # BFS with queue def has_path_sum3(root, sum): if root is None: return False queue = [(root, sum-root.val)] while queue: node, val = queue.pop(0) # popleft if node.left is None and node.right is None: if val == 0: return True if node.left is not None: queue.append((node.left, val-node.left.val)) if node.right is not None: queue.append((node.right, val-node.right.val)) return False
Given a binary tree and a sum, find all roottoleaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum 22, 5 4 8 11 13 4 7 2 5 1 return 5,4,11,2, 5,8,4,5 DFS with stack BFS with queue
def path_sum(root, sum): if root is None: return [] res = [] dfs(root, sum, [], res) return res def dfs(root, sum, ls, res): if root.left is None and root.right is None and root.val == sum: ls.append(root.val) res.append(ls) if root.left is not None: dfs(root.left, sum-root.val, ls+[root.val], res) if root.right is not None: dfs(root.right, sum-root.val, ls+[root.val], res) # DFS with stack def path_sum2(root, s): if root is None: return [] res = [] stack = [(root, [root.val])] while stack: node, ls = stack.pop() if node.left is None and node.right is None and sum(ls) == s: res.append(ls) if node.left is not None: stack.append((node.left, ls+[node.left.val])) if node.right is not None: stack.append((node.right, ls+[node.right.val])) return res # BFS with queue def path_sum3(root, sum): if root is None: return [] res = [] queue = [(root, root.val, [root.val])] while queue: node, val, ls = queue.pop(0) # popleft if node.left is None and node.right is None and val == sum: res.append(ls) if node.left is not None: queue.append((node.left, val+node.left.val, ls+[node.left.val])) if node.right is not None: queue.append((node.right, val+node.right.val, ls+[node.right.val])) return res
a Adam Book 4 b Bill Computer 5 TV 6 Jill Sports 1 c Bill Sports 3 d Adam Computer 3 Quin Computer 3 e Quin Book 5 TV 2 f Adam Computer 7
# a -> Adam -> Book -> 4 # b -> Bill -> Computer -> 5 # -> TV -> 6 # Jill -> Sports -> 1 # c -> Bill -> Sports -> 3 # d -> Adam -> Computer -> 3 # Quin -> Computer -> 3 # e -> Quin -> Book -> 5 # -> TV -> 2 # f -> Adam -> Computer -> 7 from __future__ import print_function def tree_print(tree): for key in tree: print(key, end=' ') # end=' ' prevents a newline character tree_element = tree[key] # multiple lookups is expensive, even amortized O(1)! for subElem in tree_element: print(" -> ", subElem, end=' ') if type(subElem) != str: # OP wants indenting after digits print("\n ") # newline and a space to match indenting print() # forces a newline
Implementation of RedBlack tree. set the node as the left child node of the current node's right node right node's left node become the right node of current node check the parent case set the node as the right child node of the current node's left node left node's right node become the left node of current node check the parent case the inserted node's color is default is red find the position of inserted node set the n ode's parent node case 1 inserted tree is null case 2 not null and find left or right fix the tree to case 1 the parent is null, then set the inserted node as root and color 0 case 2 the parent color is black, do nothing case 3 the parent color is red case 3.1 the uncle node is red then set parent and uncle color is black and grandparent is red then node node.parent case 3.2 the uncle node is black or null, and the node is right of parent then set his parent node is current node left rotate the node and continue the next case 3.3 the uncle node is black and parent node is left then parent node set black and grandparent set red case 3.1 the uncle node is red then set parent and uncle color is black and grandparent is red then node node.parent case 3.2 the uncle node is black or null, and the node is right of parent then set his parent node is current node left rotate the node and continue the next case 3.3 the uncle node is black and parent node is left then parent node set black and grandparent set red replace u with v :param nodeu: replaced node :param nodev: :return: None check is nodev is None find the max node when node regard as a root node :param node: :return: max node find the minimum node when node regard as a root node :param node: :return: minimum node find the node position both child exits ,and find minimum child of right child when node is black, then need to fix it with 4 cases 4 cases node is not root and color is black node is left node case 1: node's red, can not get black node set brother is black and parent is red case 2: brother node is black, and its children node is both black case 3: brother node is black , and its left child node is red and right is black case 4: brother node is black, and right is red, and left is any color
class RBNode: def __init__(self, val, is_red, parent=None, left=None, right=None): self.val = val self.parent = parent self.left = left self.right = right self.color = is_red class RBTree: def __init__(self): self.root = None def left_rotate(self, node): # set the node as the left child node of the current node's right node right_node = node.right if right_node is None: return else: # right node's left node become the right node of current node node.right = right_node.left if right_node.left is not None: right_node.left.parent = node right_node.parent = node.parent # check the parent case if node.parent is None: self.root = right_node elif node is node.parent.left: node.parent.left = right_node else: node.parent.right = right_node right_node.left = node node.parent = right_node def right_rotate(self, node): # set the node as the right child node of the current node's left node left_node = node.left if left_node is None: return else: # left node's right node become the left node of current node node.left = left_node.right if left_node.right is not None: left_node.right.parent = node left_node.parent = node.parent # check the parent case if node.parent is None: self.root = left_node elif node is node.parent.left: node.parent.left = left_node else: node.parent.right = left_node left_node.right = node node.parent = left_node def insert(self, node): # the inserted node's color is default is red root = self.root insert_node_parent = None # find the position of inserted node while root is not None: insert_node_parent = root if insert_node_parent.val < node.val: root = root.right else: root = root.left # set the n ode's parent node node.parent = insert_node_parent if insert_node_parent is None: # case 1 inserted tree is null self.root = node elif insert_node_parent.val > node.val: # case 2 not null and find left or right insert_node_parent.left = node else: insert_node_parent.right = node node.left = None node.right = None node.color = 1 # fix the tree to self.fix_insert(node) def fix_insert(self, node): # case 1 the parent is null, then set the inserted node as root and color = 0 if node.parent is None: node.color = 0 self.root = node return # case 2 the parent color is black, do nothing # case 3 the parent color is red while node.parent and node.parent.color == 1: if node.parent is node.parent.parent.left: uncle_node = node.parent.parent.right if uncle_node and uncle_node.color == 1: # case 3.1 the uncle node is red # then set parent and uncle color is black and grandparent is red # then node => node.parent node.parent.color = 0 node.parent.parent.right.color = 0 node.parent.parent.color = 1 node = node.parent.parent continue elif node is node.parent.right: # case 3.2 the uncle node is black or null, and the node is right of parent # then set his parent node is current node # left rotate the node and continue the next node = node.parent self.left_rotate(node) # case 3.3 the uncle node is black and parent node is left # then parent node set black and grandparent set red node.parent.color = 0 node.parent.parent.color = 1 self.right_rotate(node.parent.parent) else: uncle_node = node.parent.parent.left if uncle_node and uncle_node.color == 1: # case 3.1 the uncle node is red # then set parent and uncle color is black and grandparent is red # then node => node.parent node.parent.color = 0 node.parent.parent.left.color = 0 node.parent.parent.color = 1 node = node.parent.parent continue elif node is node.parent.left: # case 3.2 the uncle node is black or null, and the node is right of parent # then set his parent node is current node # left rotate the node and continue the next node = node.parent self.right_rotate(node) # case 3.3 the uncle node is black and parent node is left # then parent node set black and grandparent set red node.parent.color = 0 node.parent.parent.color = 1 self.left_rotate(node.parent.parent) self.root.color = 0 def transplant(self, node_u, node_v): """ replace u with v :param node_u: replaced node :param node_v: :return: None """ if node_u.parent is None: self.root = node_v elif node_u is node_u.parent.left: node_u.parent.left = node_v elif node_u is node_u.parent.right: node_u.parent.right = node_v # check is node_v is None if node_v: node_v.parent = node_u.parent def maximum(self, node): """ find the max node when node regard as a root node :param node: :return: max node """ temp_node = node while temp_node.right is not None: temp_node = temp_node.right return temp_node def minimum(self, node): """ find the minimum node when node regard as a root node :param node: :return: minimum node """ temp_node = node while temp_node.left: temp_node = temp_node.left return temp_node def delete(self, node): # find the node position node_color = node.color if node.left is None: temp_node = node.right self.transplant(node, node.right) elif node.right is None: temp_node = node.left self.transplant(node, node.left) else: # both child exits ,and find minimum child of right child node_min = self.minimum(node.right) node_color = node_min.color temp_node = node_min.right ## if node_min.parent is not node: self.transplant(node_min, node_min.right) node_min.right = node.right node_min.right.parent = node_min self.transplant(node, node_min) node_min.left = node.left node_min.left.parent = node_min node_min.color = node.color # when node is black, then need to fix it with 4 cases if node_color == 0: self.delete_fixup(temp_node) def delete_fixup(self, node): # 4 cases while node is not self.root and node.color == 0: # node is not root and color is black if node is node.parent.left: # node is left node node_brother = node.parent.right # case 1: node's red, can not get black node # set brother is black and parent is red if node_brother.color == 1: node_brother.color = 0 node.parent.color = 1 self.left_rotate(node.parent) node_brother = node.parent.right # case 2: brother node is black, and its children node is both black if (node_brother.left is None or node_brother.left.color == 0) and ( node_brother.right is None or node_brother.right.color == 0): node_brother.color = 1 node = node.parent else: # case 3: brother node is black , and its left child node is red and right is black if node_brother.right is None or node_brother.right.color == 0: node_brother.color = 1 node_brother.left.color = 0 self.right_rotate(node_brother) node_brother = node.parent.right # case 4: brother node is black, and right is red, and left is any color node_brother.color = node.parent.color node.parent.color = 0 node_brother.right.color = 0 self.left_rotate(node.parent) node = self.root else: node_brother = node.parent.left if node_brother.color == 1: node_brother.color = 0 node.parent.color = 1 self.left_rotate(node.parent) node_brother = node.parent.right if (node_brother.left is None or node_brother.left.color == 0) and ( node_brother.right is None or node_brother.right.color == 0): node_brother.color = 1 node = node.parent else: if node_brother.left is None or node_brother.left.color == 0: node_brother.color = 1 node_brother.right.color = 0 self.left_rotate(node_brother) node_brother = node.parent.left node_brother.color = node.parent.color node.parent.color = 0 node_brother.left.color = 0 self.right_rotate(node.parent) node = self.root node.color = 0 def inorder(self): res = [] if not self.root: return res stack = [] root = self.root while root or stack: while root: stack.append(root) root = root.left root = stack.pop() res.append({'val': root.val, 'color': root.color}) root = root.right return res if __name__ == "__main__": rb = RBTree() children = [11, 2, 14, 1, 7, 15, 5, 8, 4] for child in children: node = RBNode(child, 1) print(child) rb.insert(node) print(rb.inorder())
Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. Time Complexity OminN,M where N and M are the number of nodes for the trees. Space Complexity Ominheight1, height2 levels of recursion is the mininum height between the two trees.
def is_same_tree(tree_p, tree_q): if tree_p is None and tree_q is None: return True if tree_p is not None and tree_q is not None and tree_p.val == tree_q.val: return is_same_tree(tree_p.left, tree_q.left) and is_same_tree(tree_p.right, tree_q.right) return False # Time Complexity O(min(N,M)) # where N and M are the number of nodes for the trees. # Space Complexity O(min(height1, height2)) # levels of recursion is the mininum height between the two trees.
SegmentTree creates a segment tree with a given array and a commutative function, this nonrecursive version uses less memory than the recursive version and include: 1. range queries in logN time 2. update an element in logN time the function should be commutative and takes 2 values and returns the same type value Examples mytree SegmentTree2, 4, 5, 3, 4,max printmytree.query2, 4 mytree.update3, 6 printmytree.query0, 3 ... mytree SegmentTree4, 5, 2, 3, 4, 43, 3, lambda a, b: a b printmytree.query0, 6 mytree.update2, 10 printmytree.query0, 6 ... mytree SegmentTree1, 2, 4, 6, 4, 5, lambda a, b: a0 b0, a1 b1 printmytree.query0, 2 mytree.update2, 1, 2 printmytree.query0, 2 ...
class SegmentTree: def __init__(self, arr, function): self.tree = [None for _ in range(len(arr))] + arr self.size = len(arr) self.fn = function self.build_tree() def build_tree(self): for i in range(self.size - 1, 0, -1): self.tree[i] = self.fn(self.tree[i * 2], self.tree[i * 2 + 1]) def update(self, p, v): p += self.size self.tree[p] = v while p > 1: p = p // 2 self.tree[p] = self.fn(self.tree[p * 2], self.tree[p * 2 + 1]) def query(self, l, r): l, r = l + self.size, r + self.size res = None while l <= r: if l % 2 == 1: res = self.tree[l] if res is None else self.fn(res, self.tree[l]) if r % 2 == 0: res = self.tree[r] if res is None else self.fn(res, self.tree[r]) l, r = (l + 1) // 2, (r - 1) // 2 return res
Segmenttree creates a segment tree with a given array and function, allowing queries to be done later in logN time function takes 2 values and returns a same type value Example mytree SegmentTree2,4,5,3,4,max mytree.query2,4 mytree.query0,3 ... mytree SegmentTree4,5,2,3,4,43,3,sum mytree.query1,8 ...
class SegmentTree: def __init__(self,arr,function): self.segment = [0 for x in range(3*len(arr)+3)] self.arr = arr self.fn = function self.make_tree(0,0,len(arr)-1) def make_tree(self,i,l,r): if l==r: self.segment[i] = self.arr[l] elif l<r: self.make_tree(2*i+1,l,int((l+r)/2)) self.make_tree(2*i+2,int((l+r)/2)+1,r) self.segment[i] = self.fn(self.segment[2*i+1],self.segment[2*i+2]) def __query(self,i,L,R,l,r): if l>R or r<L or L>R or l>r: return None if L>=l and R<=r: return self.segment[i] val1 = self.__query(2*i+1,L,int((L+R)/2),l,r) val2 = self.__query(2*i+2,int((L+R+2)/2),R,l,r) print(L,R," returned ",val1,val2) if val1 != None: if val2 != None: return self.fn(val1,val2) return val1 return val2 def query(self,L,R): return self.__query(0,0,len(self.arr)-1,L,R) ''' Example - mytree = SegmentTree([2,4,5,3,4],max) mytree.query(2,4) mytree.query(0,3) ... mytree = SegmentTree([4,5,2,3,4,43,3],sum) mytree.query(1,8) ... '''
Time complexity : On In order function res if not root: return res stack while root or stack: while root: stack.appendroot root root.left root stack.pop res.appendroot.val root root.right return res def inorderrecroot, resNone:
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def inorder(root): """ In order function """ res = [] if not root: return res stack = [] while root or stack: while root: stack.append(root) root = root.left root = stack.pop() res.append(root.val) root = root.right return res def inorder_rec(root, res=None): """ Recursive Implementation """ if root is None: return [] if res is None: res = [] inorder_rec(root.left, res) res.append(root.val) inorder_rec(root.right, res) return res if __name__ == '__main__': n1 = Node(100) n2 = Node(50) n3 = Node(150) n4 = Node(25) n5 = Node(75) n6 = Node(125) n7 = Node(175) n1.left, n1.right = n2, n3 n2.left, n2.right = n4, n5 n3.left, n3.right = n6, n7 assert inorder(n1) == [25, 50, 75, 100, 125, 150, 175] assert inorder_rec(n1) == [25, 50, 75, 100, 125, 150, 175]
Given a binary tree, return the level order traversal of its nodes' values. ie, from left to right, level by level. For example: Given binary tree 3,9,20,null,null,15,7, 3 9 20 15 7 return its level order traversal as: 3, 9,20, 15,7
def level_order(root): ans = [] if not root: return ans level = [root] while level: current = [] new_level = [] for node in level: current.append(node.val) if node.left: new_level.append(node.left) if node.right: new_level.append(node.right) level = new_level ans.append(current) return ans
Time complexity : On Recursive Implementation
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def postorder(root): res_temp = [] res = [] if not root: return res stack = [] stack.append(root) while stack: root = stack.pop() res_temp.append(root.val) if root.left: stack.append(root.left) if root.right: stack.append(root.right) while res_temp: res.append(res_temp.pop()) return res # Recursive Implementation def postorder_rec(root, res=None): if root is None: return [] if res is None: res = [] postorder_rec(root.left, res) postorder_rec(root.right, res) res.append(root.val) return res
Time complexity : On This is a class of Node def initself, val, leftNone, rightNone: self.val val self.left left self.right right def preorderroot: Recursive Implementation if root is None: return if res is None: res res.appendroot.val preorderrecroot.left, res preorderrecroot.right, res return res
class Node: """ This is a class of Node """ def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def preorder(root): """ Function to Preorder """ res = [] if not root: return res stack = [] stack.append(root) while stack: root = stack.pop() res.append(root.val) if root.right: stack.append(root.right) if root.left: stack.append(root.left) return res def preorder_rec(root, res=None): """ Recursive Implementation """ if root is None: return [] if res is None: res = [] res.append(root.val) preorder_rec(root.left, res) preorder_rec(root.right, res) return res
Given a binary tree, return the zigzag level order traversal of its nodes' values. ie, from left to right, then right to left for the next level and alternate between. For example: Given binary tree 3,9,20,null,null,15,7, 3 9 20 15 7 return its zigzag level order traversal as: 3, 20,9, 15,7
def zigzag_level(root): res = [] if not root: return res level = [root] flag = 1 while level: current = [] new_level = [] for node in level: current.append(node.val) if node.left: new_level.append(node.left) if node.right: new_level.append(node.right) level = new_level res.append(current[::flag]) flag *= -1 return res
We are asked to design an efficient data structure that allows us to add and search for words. The search can be a literal word or regular expression containing ., where . can be any letter. Example: addWordbad addWorddad addWordmad searchpad false searchbad true search.ad true searchb.. true if dot if letter match xx.xx.x with yyyyyyy
import collections class TrieNode(object): def __init__(self, letter, is_terminal=False): self.children = dict() self.letter = letter self.is_terminal = is_terminal class WordDictionary(object): def __init__(self): self.root = TrieNode("") def add_word(self, word): cur = self.root for letter in word: if letter not in cur.children: cur.children[letter] = TrieNode(letter) cur = cur.children[letter] cur.is_terminal = True def search(self, word, node=None): cur = node if not cur: cur = self.root for i, letter in enumerate(word): # if dot if letter == ".": if i == len(word) - 1: # if last character for child in cur.children.itervalues(): if child.is_terminal: return True return False for child in cur.children.itervalues(): if self.search(word[i+1:], child) == True: return True return False # if letter if letter not in cur.children: return False cur = cur.children[letter] return cur.is_terminal class WordDictionary2(object): def __init__(self): self.word_dict = collections.defaultdict(list) def add_word(self, word): if word: self.word_dict[len(word)].append(word) def search(self, word): if not word: return False if '.' not in word: return word in self.word_dict[len(word)] for v in self.word_dict[len(word)]: # match xx.xx.x with yyyyyyy for i, ch in enumerate(word): if ch != v[i] and ch != '.': break else: return True return False
Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs are consist of lowercase letters az.
import collections class TrieNode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): current = self.root for letter in word: current = current.children[letter] current.is_word = True def search(self, word): current = self.root for letter in word: current = current.children.get(letter) if current is None: return False return current.is_word def starts_with(self, prefix): current = self.root for letter in prefix: current = current.children.get(letter) if current is None: return False return True
Defines the UnionFind or Disjoint Set data structure. A disjoint set is made up of a number of elements contained within another number of sets. Initially, elements are put in their own set, but sets may be merged using the unite operation. We can check if two elements are in the same seet by comparing their roots. If they are identical, the two elements are in the same set. All operations can be completed in Oan where n is the number of elements, and a the inverse ackermann function. an grows so slowly that it might as well be constant for any conceivable n. A UnionFind data structure. Consider the following sequence of events: Starting with the elements 1, 2, 3, and 4: 1 2 3 4 Initally they all live in their own sets, which means that root1 ! root3, however, if we call unite1, 3 we would then have the following: 1,3 2 4 Now we have root1 root3, but it is still the case that root1 ! root2. We may call unite2, 4 and end up with: 1,3 2,4 Again we have root1 ! root2. But after unite3, 4 we end up with: 1,2,3,4 which results in root1 root2. Add a new set containing the single element Find the root element which represents the set of a given element. That is, all elements that are in the same set will return the same root element. Finds the sets which contains the two elements and merges them into a single set. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Given a 3x3 grid, positions 0,0, 0,1, 1,2, 2,1. Initially, the 2d grid grid is filled with water. Assume 0 represents water and 1 represents land. 0 0 0 0 0 0 0 0 0 Operation 1: addLand0, 0 turns the water at grid00 into a land. 1 0 0 0 0 0 Number of islands 1 0 0 0 Operation 2: addLand0, 1 turns the water at grid01 into a land. 1 1 0 0 0 0 Number of islands 1 0 0 0 Operation 3: addLand1, 2 turns the water at grid12 into a land. 1 1 0 0 0 1 Number of islands 2 0 0 0 Operation 4: addLand2, 1 turns the water at grid21 into a land. 1 1 0 0 0 1 Number of islands 3 0 1 0
class Union: """ A Union-Find data structure. Consider the following sequence of events: Starting with the elements 1, 2, 3, and 4: {1} {2} {3} {4} Initally they all live in their own sets, which means that `root(1) != root(3)`, however, if we call `unite(1, 3)` we would then have the following: {1,3} {2} {4} Now we have `root(1) == root(3)`, but it is still the case that `root(1) != root(2)`. We may call `unite(2, 4)` and end up with: {1,3} {2,4} Again we have `root(1) != root(2)`. But after `unite(3, 4)` we end up with: {1,2,3,4} which results in `root(1) == root(2)`. """ def __init__(self): self.parents = {} self.size = {} self.count = 0 def add(self, element): """ Add a new set containing the single element """ self.parents[element] = element self.size[element] = 1 self.count += 1 def root(self, element): """ Find the root element which represents the set of a given element. That is, all elements that are in the same set will return the same root element. """ while element != self.parents[element]: self.parents[element] = self.parents[self.parents[element]] element = self.parents[element] return element def unite(self, element1, element2): """ Finds the sets which contains the two elements and merges them into a single set. """ root1, root2 = self.root(element1), self.root(element2) if root1 == root2: return if self.size[root1] > self.size[root2]: root1, root2 = root2, root1 self.parents[root1] = root2 self.size[root2] += self.size[root1] self.count -= 1 def num_islands(positions): """ Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Given a 3x3 grid, positions = [[0,0], [0,1], [1,2], [2,1]]. Initially, the 2d grid grid is filled with water. (Assume 0 represents water and 1 represents land). 0 0 0 0 0 0 0 0 0 Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. 1 0 0 0 0 0 Number of islands = 1 0 0 0 Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. 1 1 0 0 0 0 Number of islands = 1 0 0 0 Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. 1 1 0 0 0 1 Number of islands = 2 0 0 0 Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. 1 1 0 0 0 1 Number of islands = 3 0 1 0 """ ans = [] islands = Union() for position in map(tuple, positions): islands.add(position) for delta in (0, 1), (0, -1), (1, 0), (-1, 0): adjacent = (position[0] + delta[0], position[1] + delta[1]) if adjacent in islands.parents: islands.unite(position, adjacent) ans += [islands.count] return ans
Get a full absolute path a file
import os def full_path(file): return os.path.abspath(os.path.expanduser(file))
Both URL and file path joins use slashes as dividers between their parts. For example: pathtodir file pathtodirfile pathtodir file pathtodirfile http:algorithms.com part http:algorithms.compart http:algorithms.com part http:algorithmspart Remove trailing Remove leading
import os def join_with_slash(base, suffix): # Remove / trailing base = base.rstrip('/') # Remove / leading suffix = suffix.lstrip('/').rstrip() full_path = "{}/{}".format(base, suffix) return full_path
Given an absolute path for a file Unixstyle, simplify it. For example, path home, home path a.b....c, c Corner Cases: Did you consider the case where path ..? In this case, you should return . Another corner case is the path might contain multiple slashes '' together, such as homefoo. In this case, you should ignore redundant slashes and return homefoo. Reference: https:leetcode.comproblemssimplifypathdescription
import os def simplify_path_v1(path): return os.path.abspath(path) def simplify_path_v2(path): stack, tokens = [], path.split("/") for token in tokens: if token == ".." and stack: stack.pop() elif token != ".." and token != "." and token: stack.append(token) return "/" + "/".join(stack)
Splitting a path into 2 parts Example: Input: https:algorithmsunixtest.py for url Output: part0: https:algorithmsunix part1: test.py Input: algorithmsunixtest.py for file path Output: part0: algorithmsunix part1: test.py Takt the origin path without the last part Take the last element of list
import os def split(path): parts = [] split_part = path.rpartition('/') # Takt the origin path without the last part parts.append(split_part[0]) # Take the last element of list parts.append(split_part[2]) return parts
!usrbinenv python3 coding: utf8 algorithms documentation build configuration file, created by sphinxquickstart on Wed Jun 6 01:17:26 2018. This file is execfiled with the current directory set to its containing dir. Note that not all possible configuration values are present in this autogenerated file. All configuration values have a default; values that are commented out serve to show the default. If extensions or modules to document with autodoc are in another directory, add these directories to sys.path here. If the directory is relative to the documentation root, use os.path.abspath to make it absolute, like shown here. import os import sys sys.path.insert0, os.path.abspath'.' General configuration If your documentation needs a minimal Sphinx version, state it here. needssphinx '1.0' Add any Sphinx extension module names here, as strings. They can be extensions coming with Sphinx named 'sphinx.ext.' or your custom ones. Add any paths that contain templates here, relative to this directory. The suffixes of source filenames. You can specify multiple suffix as a list of string: The master toctree document. General information about the project. The version info for the project you're documenting, acts as replacement for version and release, also used in various other places throughout the built documents. The short X.Y version. The full version, including alphabetarc tags. The language for content autogenerated by Sphinx. Refer to documentation for a list of supported languages. This is also used if you do content translation via gettext catalogs. Usually you set language from the command line for these cases. List of patterns, relative to source directory, that match files and directories to ignore when looking for source files. This patterns also effect to htmlstaticpath and htmlextrapath The name of the Pygments syntax highlighting style to use. If true, todo and todoList produce output, else they produce nothing. Options for HTML output The theme to use for HTML and HTML Help pages. See the documentation for a list of builtin themes. Theme options are themespecific and customize the look and feel of a theme further. For a list of options available for each theme, see the documentation. htmlthemeoptions Add any paths that contain custom static files such as style sheets here, relative to this directory. They are copied after the builtin static files, so a file named default.css will overwrite the builtin default.css. Custom sidebar templates, must be a dictionary that maps document names to template names. This is required for the alabaster theme refs: http:alabaster.readthedocs.ioenlatestinstallation.htmlsidebars Options for HTMLHelp output Output file base name for HTML help builder. Options for LaTeX output The paper size 'letterpaper' or 'a4paper'. 'papersize': 'letterpaper', The font size '10pt', '11pt' or '12pt'. 'pointsize': '10pt', Additional stuff for the LaTeX preamble. 'preamble': '', Latex figure float alignment 'figurealign': 'htbp', Grouping the document tree into LaTeX files. List of tuples source start file, target name, title, author, documentclass howto, manual, or own class. Options for manual page output One entry per manual page. List of tuples source start file, name, description, authors, manual section. Options for Texinfo output Grouping the document tree into Texinfo files. List of tuples source start file, target name, title, author, dir menu entry, description, category
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # algorithms documentation build configuration file, created by # sphinx-quickstart on Wed Jun 6 01:17:26 2018. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) from recommonmark.parser import CommonMarkParser # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_parsers = { '.md': CommonMarkParser } source_suffix = ['.rst', '.md'] # The master toctree document. master_doc = 'index' # General information about the project. project = 'algorithms' copyright = '2018, Algorithms Team & Contributors' author = 'Algorithms Team & Contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1.0' # The full version, including alpha/beta/rc tags. release = '0.1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { '**': [ 'about.html', 'searchbox.html', 'navigation.html', 'relations.html', # needs 'show_related': True theme option to display ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'algorithmsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'algorithms.tex', 'algorithms Documentation', 'Algorithms Team \\& Contributors', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'algorithms', 'algorithms Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'algorithms', 'algorithms Documentation', author, 'algorithms', 'One line description of project.', 'Miscellaneous'), ]
123, 6 123, 123 232, 8 232, 232
from algorithms.backtrack import ( add_operators, permute_iter, anagram, array_sum_combinations, unique_array_sum_combinations, combination_sum, get_factors, recursive_get_factors, find_words, generate_abbreviations, generate_parenthesis_v1, generate_parenthesis_v2, letter_combinations, palindromic_substrings, pattern_match, permute_unique, permute, permute_recursive, subsets_unique, subsets, subsets_v2, ) import unittest class TestAddOperator(unittest.TestCase): def test_add_operators(self): # "123", 6 -> ["1+2+3", "1*2*3"] s = "123" target = 6 self.assertEqual(add_operators(s, target), ["1+2+3", "1*2*3"]) # "232", 8 -> ["2*3+2", "2+3*2"] s = "232" target = 8 self.assertEqual(add_operators(s, target), ["2+3*2", "2*3+2"]) s = "123045" target = 3 answer = ['1+2+3*0*4*5', '1+2+3*0*45', '1+2-3*0*4*5', '1+2-3*0*45', '1-2+3+0-4+5', '1-2+3-0-4+5', '1*2+3*0-4+5', '1*2-3*0-4+5', '1*23+0-4*5', '1*23-0-4*5', '12+3*0-4-5', '12-3*0-4-5'] self.assertEqual(add_operators(s, target), answer) class TestPermuteAndAnagram(unittest.TestCase): def test_permute(self): perms = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba'] self.assertEqual(perms, permute("abc")) def test_permute_iter(self): it = permute_iter("abc") perms = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba'] for i in range(len(perms)): self.assertEqual(perms[i], next(it)) def test_angram(self): self.assertTrue(anagram('apple', 'pleap')) self.assertFalse(anagram("apple", "cherry")) class TestArrayCombinationSum(unittest.TestCase): def test_array_sum_combinations(self): A = [1, 2, 3, 3] B = [2, 3, 3, 4] C = [2, 3, 3, 4] target = 7 answer = [[1, 2, 4], [1, 3, 3], [1, 3, 3], [1, 3, 3], [1, 3, 3], [1, 4, 2], [2, 2, 3], [2, 2, 3], [2, 3, 2], [2, 3, 2], [3, 2, 2], [3, 2, 2]] answer.sort() self.assertListEqual(sorted(array_sum_combinations(A, B, C, target)), answer) def test_unique_array_sum_combinations(self): A = [1, 2, 3, 3] B = [2, 3, 3, 4] C = [2, 3, 3, 4] target = 7 answer = [(2, 3, 2), (3, 2, 2), (1, 2, 4), (1, 4, 2), (2, 2, 3), (1, 3, 3)] answer.sort() self.assertListEqual(sorted(unique_array_sum_combinations(A, B, C, target)), answer) class TestCombinationSum(unittest.TestCase): def check_sum(self, nums, target): if sum(nums) == target: return (True, nums) else: return (False, nums) def test_combination_sum(self): candidates1 = [2, 3, 6, 7] target1 = 7 answer1 = [ [2, 2, 3], [7] ] self.assertEqual(combination_sum(candidates1, target1), answer1) candidates2 = [2, 3, 5] target2 = 8 answer2 = [ [2, 2, 2, 2], [2, 3, 3], [3, 5] ] self.assertEqual(combination_sum(candidates2, target2), answer2) class TestFactorCombinations(unittest.TestCase): def test_get_factors(self): target1 = 32 answer1 = [ [2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8] ] self.assertEqual(sorted(get_factors(target1)), sorted(answer1)) target2 = 12 answer2 = [ [2, 6], [2, 2, 3], [3, 4] ] self.assertEqual(sorted(get_factors(target2)), sorted(answer2)) self.assertEqual(sorted(get_factors(1)), []) self.assertEqual(sorted(get_factors(37)), []) def test_recursive_get_factors(self): target1 = 32 answer1 = [ [2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8] ] self.assertEqual(sorted(recursive_get_factors(target1)), sorted(answer1)) target2 = 12 answer2 = [ [2, 6], [2, 2, 3], [3, 4] ] self.assertEqual(sorted(recursive_get_factors(target2)), sorted(answer2)) self.assertEqual(sorted(recursive_get_factors(1)), []) self.assertEqual(sorted(recursive_get_factors(37)), []) class TestFindWords(unittest.TestCase): def test_normal(self): board = [ ['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'], ['i', 'h', 'k', 'r'], ['i', 'f', 'l', 'v'] ] words = ["oath", "pea", "eat", "rain"] result = find_words(board, words) test_result = ['oath', 'eat'] self.assertEqual(sorted(result),sorted(test_result)) def test_none(self): board = [ ['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'], ['i', 'h', 'k', 'r'], ['i', 'f', 'l', 'v'] ] words = ["chicken", "nugget", "hello", "world"] self.assertEqual(find_words(board, words), []) def test_empty(self): board = [] words = [] self.assertEqual(find_words(board, words), []) def test_uneven(self): board = [ ['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'] ] words = ["oath", "pea", "eat", "rain"] self.assertEqual(find_words(board, words), ['eat']) def test_repeat(self): board = [ ['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a'] ] words = ["a", "aa", "aaa", "aaaa", "aaaaa"] self.assertTrue(len(find_words(board, words)) == 5) class TestGenerateAbbreviations(unittest.TestCase): def test_generate_abbreviations(self): word1 = "word" answer1 = ['word', 'wor1', 'wo1d', 'wo2', 'w1rd', 'w1r1', 'w2d', 'w3', '1ord', '1or1', '1o1d', '1o2', '2rd', '2r1', '3d', '4'] self.assertEqual(sorted(generate_abbreviations(word1)), sorted(answer1)) word2 = "hello" answer2 = ['hello', 'hell1', 'hel1o', 'hel2', 'he1lo', 'he1l1', 'he2o', 'he3', 'h1llo', 'h1ll1', 'h1l1o', 'h1l2', 'h2lo', 'h2l1', 'h3o', 'h4', '1ello', '1ell1', '1el1o', '1el2', '1e1lo', '1e1l1', '1e2o', '1e3', '2llo', '2ll1', '2l1o', '2l2', '3lo', '3l1', '4o', '5'] self.assertEqual(sorted(generate_abbreviations(word2)), sorted(answer2)) class TestPatternMatch(unittest.TestCase): def test_pattern_match(self): pattern1 = "abab" string1 = "redblueredblue" pattern2 = "aaaa" string2 = "asdasdasdasd" pattern3 = "aabb" string3 = "xyzabcxzyabc" self.assertTrue(pattern_match(pattern1, string1)) self.assertTrue(pattern_match(pattern2, string2)) self.assertFalse(pattern_match(pattern3, string3)) class TestGenerateParenthesis(unittest.TestCase): def test_generate_parenthesis(self): self.assertEqual(generate_parenthesis_v1(2), ['()()', '(())']) self.assertEqual(generate_parenthesis_v1(3), ['()()()', '()(())', '(())()', '(()())', '((()))']) self.assertEqual(generate_parenthesis_v2(2), ['(())', '()()']) self.assertEqual(generate_parenthesis_v2(3), ['((()))', '(()())', '(())()', '()(())', '()()()']) class TestLetterCombinations(unittest.TestCase): def test_letter_combinations(self): digit1 = "23" answer1 = ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] self.assertEqual(sorted(letter_combinations(digit1)), sorted(answer1)) digit2 = "34" answer2 = ['dg', 'dh', 'di', 'eg', 'eh', 'ei', 'fg', 'fh', 'fi'] self.assertEqual(sorted(letter_combinations(digit2)), sorted(answer2)) class TestPalindromicSubstrings(unittest.TestCase): def test_palindromic_substrings(self): string1 = "abc" answer1 = [['a', 'b', 'c']] self.assertEqual(palindromic_substrings(string1), sorted(answer1)) string2 = "abcba" answer2 = [['abcba'], ['a', 'bcb', 'a'], ['a', 'b', 'c', 'b', 'a']] self.assertEqual(sorted(palindromic_substrings(string2)), sorted(answer2)) string3 = "abcccba" answer3 = [['abcccba'], ['a', 'bcccb', 'a'], ['a', 'b', 'ccc', 'b', 'a'], ['a', 'b', 'cc', 'c', 'b', 'a'], ['a', 'b', 'c', 'cc', 'b', 'a'], ['a', 'b', 'c', 'c', 'c', 'b', 'a']] self.assertEqual(sorted(palindromic_substrings(string3)), sorted(answer3)) class TestPermuteUnique(unittest.TestCase): def test_permute_unique(self): nums1 = [1, 1, 2] answer1 = [[2, 1, 1], [1, 2, 1], [1, 1, 2]] self.assertEqual(sorted(permute_unique(nums1)), sorted(answer1)) nums2 = [1, 2, 1, 3] answer2 = [[3, 1, 2, 1], [1, 3, 2, 1], [1, 2, 3, 1], [1, 2, 1, 3], [3, 2, 1, 1], [2, 3, 1, 1], [2, 1, 3, 1], [2, 1, 1, 3], [3, 1, 1, 2], [1, 3, 1, 2], [1, 1, 3, 2], [1, 1, 2, 3]] self.assertEqual(sorted(permute_unique(nums2)), sorted(answer2)) nums3 = [1, 2, 3] answer3 = [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]] self.assertEqual(sorted(permute_unique(nums3)), sorted(answer3)) class TestPermute(unittest.TestCase): def test_permute(self): nums1 = [1, 2, 3, 4] answer1 = [[1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4], [2, 3, 4, 1], [1, 3, 2, 4], [3, 1, 2, 4], [3, 2, 1, 4], [3, 2, 4, 1], [1, 3, 4, 2], [3, 1, 4, 2], [3, 4, 1, 2], [3, 4, 2, 1], [1, 2, 4, 3], [2, 1, 4, 3], [2, 4, 1, 3], [2, 4, 3, 1], [1, 4, 2, 3], [4, 1, 2, 3], [4, 2, 1, 3], [4, 2, 3, 1], [1, 4, 3, 2], [4, 1, 3, 2], [4, 3, 1, 2], [4, 3, 2, 1]] self.assertEqual(sorted(permute(nums1)), sorted(answer1)) nums2 = [1, 2, 3] answer2 = [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]] self.assertEqual(sorted(permute(nums2)), sorted(answer2)) def test_permute_recursive(self): nums1 = [1, 2, 3, 4] answer1 = [[1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4], [2, 3, 4, 1], [1, 3, 2, 4], [3, 1, 2, 4], [3, 2, 1, 4], [3, 2, 4, 1], [1, 3, 4, 2], [3, 1, 4, 2], [3, 4, 1, 2], [3, 4, 2, 1], [1, 2, 4, 3], [2, 1, 4, 3], [2, 4, 1, 3], [2, 4, 3, 1], [1, 4, 2, 3], [4, 1, 2, 3], [4, 2, 1, 3], [4, 2, 3, 1], [1, 4, 3, 2], [4, 1, 3, 2], [4, 3, 1, 2], [4, 3, 2, 1]] self.assertEqual(sorted(permute_recursive(nums1)), sorted(answer1)) nums2 = [1, 2, 3] answer2 = [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]] self.assertEqual(sorted(permute_recursive(nums2)), sorted(answer2)) class TestSubsetsUnique(unittest.TestCase): def test_subsets_unique(self): nums1 = [1, 2, 2] answer1 = [(1, 2), (1,), (1, 2, 2), (2,), (), (2, 2)] self.assertEqual(sorted(subsets_unique(nums1)), sorted(answer1)) nums2 = [1, 2, 3, 4] answer2 = [(1, 2), (1, 3), (1, 2, 3, 4), (1,), (2,), (3,), (1, 4), (1, 2, 3), (4,), (), (2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (3, 4), (2, 4)] self.assertEqual(sorted(subsets_unique(nums2)), sorted(answer2)) class TestSubsets(unittest.TestCase): def test_subsets(self): nums1 = [1, 2, 3] answer1 = [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []] self.assertEqual(sorted(subsets(nums1)), sorted(answer1)) nums2 = [1, 2, 3, 4] answer2 = [[1, 2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2], [1, 3, 4], [1, 3], [1, 4], [1], [2, 3, 4], [2, 3], [2, 4], [2], [3, 4], [3], [4], []] self.assertEqual(sorted(subsets(nums2)), sorted(answer2)) def test_subsets_v2(self): nums1 = [1, 2, 3] answer1 = [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []] self.assertEqual(sorted(subsets_v2(nums1)), sorted(answer1)) nums2 = [1, 2, 3, 4] answer2 = [[1, 2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2], [1, 3, 4], [1, 3], [1, 4], [1], [2, 3, 4], [2, 3], [2, 4], [2], [3, 4], [3], [4], []] self.assertEqual(sorted(subsets_v2(nums2)), sorted(answer2)) if __name__ == '__main__': unittest.main()
hit hot dot dog cog pick sick sink sank tank 5 live life 1, no matter what is the wordlist. 0 length from ate ate not possible to reach !
from algorithms.bfs import ( count_islands, maze_search, ladder_length ) import unittest class TestCountIslands(unittest.TestCase): def test_count_islands(self): grid_1 = [[1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0]] self.assertEqual(1, count_islands(grid_1)) grid_2 = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1]] self.assertEqual(3, count_islands(grid_2)) grid_3 = [[1, 1, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1], [0, 0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 0]] self.assertEqual(3, count_islands(grid_3)) grid_4 = [[1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 0, 0]] self.assertEqual(5, count_islands(grid_4)) class TestMazeSearch(unittest.TestCase): def test_maze_search(self): grid_1 = [[1, 0, 1, 1, 1, 1], [1, 0, 1, 0, 1, 0], [1, 0, 1, 0, 1, 1], [1, 1, 1, 0, 1, 1]] self.assertEqual(14, maze_search(grid_1)) grid_2 = [[1, 0, 0], [0, 1, 1], [0, 1, 1]] self.assertEqual(-1, maze_search(grid_2)) class TestWordLadder(unittest.TestCase): def test_ladder_length(self): # hit -> hot -> dot -> dog -> cog self.assertEqual(5, ladder_length('hit', 'cog', ["hot", "dot", "dog", "lot", "log"])) # pick -> sick -> sink -> sank -> tank == 5 self.assertEqual(5, ladder_length('pick', 'tank', ['tock', 'tick', 'sank', 'sink', 'sick'])) # live -> life == 1, no matter what is the word_list. self.assertEqual(1, ladder_length('live', 'life', ['hoho', 'luck'])) # 0 length from ate -> ate self.assertEqual(0, ladder_length('ate', 'ate', [])) # not possible to reach ! self.assertEqual(-1, ladder_length('rahul', 'coder', ['blahh', 'blhah'])) if __name__ == "__main__": unittest.main()
Initialize seed. random.seedtest def testaddbitwiseoperatorself: self.assertEqual5432 97823, addbitwiseoperator5432, 97823 self.assertEqual0, addbitwiseoperator0, 0 self.assertEqual10, addbitwiseoperator10, 0 self.assertEqual10, addbitwiseoperator0, 10 def testcountonesrecurself: 8 1000 self.assertEqual1, countonesrecur8 109 1101101 self.assertEqual5, countonesrecur109 63 111111 self.assertEqual6, countonesrecur63 0 0 self.assertEqual0, countonesrecur0 def testcountonesiterself: 8 1000 self.assertEqual1, countonesiter8 109 1101101 self.assertEqual5, countonesiter109 63 111111 self.assertEqual6, countonesiter63 0 0 self.assertEqual0, countonesiter0 def testcountflipstoconvertself: 29: 11101 and 15: 01111 self.assertEqual2, countflipstoconvert29, 15 45: 0000101101 and 987: 1111011011 self.assertEqual8, countflipstoconvert45, 987 34: 100010 self.assertEqual0, countflipstoconvert34, 34 34: 100010 and 53: 110101 self.assertEqual4, countflipstoconvert34, 53 def testfindmissingnumberself: self.assertEqual7, findmissingnumber4, 1, 3, 0, 6, 5, 2 self.assertEqual0, findmissingnumber1 self.assertEqual1, findmissingnumber0 nums i for i in range100000 if i ! 12345 random.shufflenums self.assertEqual12345, findmissingnumbernums def testfindmissingnumber2self: self.assertEqual7, findmissingnumber24, 1, 3, 0, 6, 5, 2 self.assertEqual0, findmissingnumber21 self.assertEqual1, findmissingnumber20 nums i for i in range100000 if i ! 12345 random.shufflenums self.assertEqual12345, findmissingnumber2nums def testflipbitlongestseqself: 1775: 11011101111 self.assertEqual8, flipbitlongestseq1775 5: 101 self.assertEqual3, flipbitlongestseq5 71: 1000111 self.assertEqual4, flipbitlongestseq71 0: 0 self.assertEqual1, flipbitlongestseq0 def testispoweroftwoself: self.assertTrueispoweroftwo64 self.assertFalseispoweroftwo91 self.assertTrueispoweroftwo21001 self.assertTrueispoweroftwo1 self.assertFalseispoweroftwo0 def testreversebitsself: self.assertEqual43261596, reversebits964176192 self.assertEqual964176192, reversebits43261596 self.assertEqual1, reversebits2147483648 bin0 00000000000000000000000000000000 self.assertEqual0, reversebits0 bin232 1 11111111111111111111111111111111 self.assertEqual232 1, reversebits232 1 def testsinglenumberself: random.seed'test' self.assertEqual0, singlenumber1, 0, 2, 1, 2, 3, 3 self.assertEqual101, singlenumber101 single random.randint1, 100000 nums random.randint1, 100000 for in range1000 nums 2 nums contains pairs of random integers nums.appendsingle random.shufflenums self.assertEqualsingle, singlenumbernums def testsinglenumber2self: self.assertEqual3, singlenumber24, 2, 3, 2, 1, 1, 4, 2, 4, 1 single random.randint1, 100000 nums random.randint1, 100000 for in range1000 nums 3 nums contains triplets of random integers nums.appendsingle random.shufflenums self.assertEqualsingle, singlenumber2nums def testsinglenumber3self: self.assertEqualsorted2, 5, sortedsinglenumber32, 1, 5, 6, 6, 1 self.assertEqualsorted4, 3, sortedsinglenumber39, 9, 4, 3 def testsubsetsself: self.assertSetEqualsubsets1, 2, 3, , 1,, 2,, 3,, 1, 2, 1, 3, 2, 3, 1, 2, 3 self.assertSetEqualsubsets10, 20, 30, 40, 10, 40, 10, 20, 40, 10, 30, 10, 20, 30, 40, 40,, 10, 30, 40, 30,, 20, 30, 30, 40, 10,, , 10, 20, 20, 40, 20, 30, 40, 10, 20, 30, 20, def testgetbitself: 22 10110 self.assertEqual1, getbit22, 2 self.assertEqual0, getbit22, 3 def testsetbitself: 22 10110 after set bit at 3th position: 30 11110 self.assertEqual30, setbit22, 3 def testclearbitself: 22 10110 after clear bit at 2nd position: 20 10010 self.assertEqual18, clearbit22, 2 def testupdatebitself: 22 10110 after update bit at 3th position with value 1: 30 11110 self.assertEqual30, updatebit22, 3, 1 22 10110 after update bit at 2nd position with value 0: 20 10010 self.assertEqual18, updatebit22, 2, 0 def testinttobytesbigendianself: self.assertEqualb'x11', inttobytesbigendian17 def testinttobyteslittleendianself: self.assertEqualb'x11', inttobyteslittleendian17 def testbytesbigendiantointself: self.assertEqual17, bytesbigendiantointb'x11' def testbyteslittleendiantointself: self.assertEqual17, byteslittleendiantointb'x11' def testswappairself: 22: 10110 41: 101001 self.assertEqual41, swappair22 10: 1010 5 : 0101 self.assertEqual5, swappair10 def testfinddifferenceself: self.assertEqual'e', finddifferenceabcd, abecd def testhasalternativebitself: self.assertTruehasalternativebit5 self.assertFalsehasalternativebit7 self.assertFalsehasalternativebit11 self.assertTruehasalternativebit10 def testhasalternativebitfastself: self.assertTruehasalternativebitfast5 self.assertFalsehasalternativebitfast7 self.assertFalsehasalternativebitfast11 self.assertTruehasalternativebitfast10 def testinsertonebitself: self.assertEqual45, insertonebit21, 1, 2 self.assertEqual41, insertonebit21, 0, 2 self.assertEqual53, insertonebit21, 1, 5 self.assertEqual43, insertonebit21, 1, 0 def testinsertmultbitsself: self.assertEqual47, insertmultbits5, 7, 3, 1 self.assertEqual47, insertmultbits5, 7, 3, 0 self.assertEqual61, insertmultbits5, 7, 3, 3 def testremovebitself: self.assertEqual9, removebit21, 2 self.assertEqual5, removebit21, 4 self.assertEqual10, removebit21, 0 def testbinarygapself: 22 10110 self.assertEqual2, binarygap22 6 110 self.assertEqual1, binarygap6 8 1000 self.assertEqual0, binarygap8 145 10010001 self.assertEqual4, binarygap145 if name 'main': unittest.main
from algorithms.bit import ( add_bitwise_operator, count_ones_iter, count_ones_recur, count_flips_to_convert, find_missing_number, find_missing_number2, flip_bit_longest_seq, is_power_of_two, reverse_bits, single_number, single_number2, single_number3, subsets, get_bit, set_bit, clear_bit, update_bit, int_to_bytes_big_endian, int_to_bytes_little_endian, bytes_big_endian_to_int, bytes_little_endian_to_int, swap_pair, find_difference, has_alternative_bit, has_alternative_bit_fast, insert_one_bit, insert_mult_bits, remove_bit, binary_gap ) import unittest import random class TestSuite(unittest.TestCase): def setUp(self): """Initialize seed.""" random.seed("test") def test_add_bitwise_operator(self): self.assertEqual(5432 + 97823, add_bitwise_operator(5432, 97823)) self.assertEqual(0, add_bitwise_operator(0, 0)) self.assertEqual(10, add_bitwise_operator(10, 0)) self.assertEqual(10, add_bitwise_operator(0, 10)) def test_count_ones_recur(self): # 8 -> 1000 self.assertEqual(1, count_ones_recur(8)) # 109 -> 1101101 self.assertEqual(5, count_ones_recur(109)) # 63 -> 111111 self.assertEqual(6, count_ones_recur(63)) # 0 -> 0 self.assertEqual(0, count_ones_recur(0)) def test_count_ones_iter(self): # 8 -> 1000 self.assertEqual(1, count_ones_iter(8)) # 109 -> 1101101 self.assertEqual(5, count_ones_iter(109)) # 63 -> 111111 self.assertEqual(6, count_ones_iter(63)) # 0 -> 0 self.assertEqual(0, count_ones_iter(0)) def test_count_flips_to_convert(self): # 29: 11101 and 15: 01111 self.assertEqual(2, count_flips_to_convert(29, 15)) # 45: 0000101101 and 987: 1111011011 self.assertEqual(8, count_flips_to_convert(45, 987)) # 34: 100010 self.assertEqual(0, count_flips_to_convert(34, 34)) # 34: 100010 and 53: 110101 self.assertEqual(4, count_flips_to_convert(34, 53)) def test_find_missing_number(self): self.assertEqual(7, find_missing_number([4, 1, 3, 0, 6, 5, 2])) self.assertEqual(0, find_missing_number([1])) self.assertEqual(1, find_missing_number([0])) nums = [i for i in range(100000) if i != 12345] random.shuffle(nums) self.assertEqual(12345, find_missing_number(nums)) def test_find_missing_number2(self): self.assertEqual(7, find_missing_number2([4, 1, 3, 0, 6, 5, 2])) self.assertEqual(0, find_missing_number2([1])) self.assertEqual(1, find_missing_number2([0])) nums = [i for i in range(100000) if i != 12345] random.shuffle(nums) self.assertEqual(12345, find_missing_number2(nums)) def test_flip_bit_longest_seq(self): # 1775: 11011101111 self.assertEqual(8, flip_bit_longest_seq(1775)) # 5: 101 self.assertEqual(3, flip_bit_longest_seq(5)) # 71: 1000111 self.assertEqual(4, flip_bit_longest_seq(71)) # 0: 0 self.assertEqual(1, flip_bit_longest_seq(0)) def test_is_power_of_two(self): self.assertTrue(is_power_of_two(64)) self.assertFalse(is_power_of_two(91)) self.assertTrue(is_power_of_two(2**1001)) self.assertTrue(is_power_of_two(1)) self.assertFalse(is_power_of_two(0)) def test_reverse_bits(self): self.assertEqual(43261596, reverse_bits(964176192)) self.assertEqual(964176192, reverse_bits(43261596)) self.assertEqual(1, reverse_bits(2147483648)) # bin(0) => 00000000000000000000000000000000 self.assertEqual(0, reverse_bits(0)) # bin(2**32 - 1) => 11111111111111111111111111111111 self.assertEqual(2**32 - 1, reverse_bits(2**32 - 1)) def test_single_number(self): random.seed('test') self.assertEqual(0, single_number([1, 0, 2, 1, 2, 3, 3])) self.assertEqual(101, single_number([101])) single = random.randint(1, 100000) nums = [random.randint(1, 100000) for _ in range(1000)] nums *= 2 # nums contains pairs of random integers nums.append(single) random.shuffle(nums) self.assertEqual(single, single_number(nums)) def test_single_number2(self): self.assertEqual(3, single_number2([4, 2, 3, 2, 1, 1, 4, 2, 4, 1])) single = random.randint(1, 100000) nums = [random.randint(1, 100000) for _ in range(1000)] nums *= 3 # nums contains triplets of random integers nums.append(single) random.shuffle(nums) self.assertEqual(single, single_number2(nums)) def test_single_number3(self): self.assertEqual(sorted([2, 5]), sorted(single_number3([2, 1, 5, 6, 6, 1]))) self.assertEqual(sorted([4, 3]), sorted(single_number3([9, 9, 4, 3]))) def test_subsets(self): self.assertSetEqual(subsets([1, 2, 3]), {(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)}) self.assertSetEqual(subsets([10, 20, 30, 40]), {(10, 40), (10, 20, 40), (10, 30), (10, 20, 30, 40), (40,), (10, 30, 40), (30,), (20, 30), (30, 40), (10,), (), (10, 20), (20, 40), (20, 30, 40), (10, 20, 30), (20,)}) def test_get_bit(self): # 22 = 10110 self.assertEqual(1, get_bit(22, 2)) self.assertEqual(0, get_bit(22, 3)) def test_set_bit(self): # 22 = 10110 --> after set bit at 3th position: 30 = 11110 self.assertEqual(30, set_bit(22, 3)) def test_clear_bit(self): # 22 = 10110 --> after clear bit at 2nd position: 20 = 10010 self.assertEqual(18, clear_bit(22, 2)) def test_update_bit(self): # 22 = 10110 --> after update bit at 3th position with # value 1: 30 = 11110 self.assertEqual(30, update_bit(22, 3, 1)) # 22 = 10110 --> after update bit at 2nd position with # value 0: 20 = 10010 self.assertEqual(18, update_bit(22, 2, 0)) def test_int_to_bytes_big_endian(self): self.assertEqual(b'\x11', int_to_bytes_big_endian(17)) def test_int_to_bytes_little_endian(self): self.assertEqual(b'\x11', int_to_bytes_little_endian(17)) def test_bytes_big_endian_to_int(self): self.assertEqual(17, bytes_big_endian_to_int(b'\x11')) def test_bytes_little_endian_to_int(self): self.assertEqual(17, bytes_little_endian_to_int(b'\x11')) def test_swap_pair(self): # 22: 10110 --> 41: 101001 self.assertEqual(41, swap_pair(22)) # 10: 1010 --> 5 : 0101 self.assertEqual(5, swap_pair(10)) def test_find_difference(self): self.assertEqual('e', find_difference("abcd", "abecd")) def test_has_alternative_bit(self): self.assertTrue(has_alternative_bit(5)) self.assertFalse(has_alternative_bit(7)) self.assertFalse(has_alternative_bit(11)) self.assertTrue(has_alternative_bit(10)) def test_has_alternative_bit_fast(self): self.assertTrue(has_alternative_bit_fast(5)) self.assertFalse(has_alternative_bit_fast(7)) self.assertFalse(has_alternative_bit_fast(11)) self.assertTrue(has_alternative_bit_fast(10)) def test_insert_one_bit(self): """ Input: num = 10101 (21) insert_one_bit(num, 1, 2): 101101 (45) insert_one_bit(num, 0 ,2): 101001 (41) insert_one_bit(num, 1, 5): 110101 (53) insert_one_bit(num, 1, 0): 101010 (42) """ self.assertEqual(45, insert_one_bit(21, 1, 2)) self.assertEqual(41, insert_one_bit(21, 0, 2)) self.assertEqual(53, insert_one_bit(21, 1, 5)) self.assertEqual(43, insert_one_bit(21, 1, 0)) def test_insert_mult_bits(self): """ Input: num = 101 (5) insert_mult_bits(num, 7, 3, 1): 101111 (47) insert_mult_bits(num, 7, 3, 0): 101111 (47) insert_mult_bits(num, 7, 3, 3): 111101 (61) """ self.assertEqual(47, insert_mult_bits(5, 7, 3, 1)) self.assertEqual(47, insert_mult_bits(5, 7, 3, 0)) self.assertEqual(61, insert_mult_bits(5, 7, 3, 3)) def test_remove_bit(self): """ Input: num = 10101 (21) remove_bit(num, 2): output = 1001 (9) remove_bit(num, 4): output = 101 (5) remove_bit(num, 0): output = 1010 (10) """ self.assertEqual(9, remove_bit(21, 2)) self.assertEqual(5, remove_bit(21, 4)) self.assertEqual(10, remove_bit(21, 0)) def test_binary_gap(self): # 22 = 10110 self.assertEqual(2, binary_gap(22)) # 6 = 110 self.assertEqual(1, binary_gap(6)) # 8 = 1000 self.assertEqual(0, binary_gap(8)) # 145 = 10010001 self.assertEqual(4, binary_gap(145)) if __name__ == '__main__': unittest.main()
summary Test for the file hosoyatriangle Arguments: unittest type description Test 1 Test 2 Test 3 Test 4 Test 5 arrange act assert arrange act assert E.g. s a b b p 1 0 0 0 a 0 1 0 0 b 0 0 1 0 0 1 1 1
from algorithms.dp import ( max_profit_naive, max_profit_optimized, climb_stairs, climb_stairs_optimized, count, combination_sum_topdown, combination_sum_bottom_up, edit_distance, egg_drop, fib_recursive, fib_list, fib_iter, hosoya_testing, house_robber, Job, schedule, Item, get_maximum_value, longest_increasing_subsequence, longest_increasing_subsequence_optimized, longest_increasing_subsequence_optimized2, int_divide,find_k_factor, planting_trees, regex_matching ) import unittest class TestBuySellStock(unittest.TestCase): def test_max_profit_naive(self): self.assertEqual(max_profit_naive([7, 1, 5, 3, 6, 4]), 5) self.assertEqual(max_profit_naive([7, 6, 4, 3, 1]), 0) def test_max_profit_optimized(self): self.assertEqual(max_profit_optimized([7, 1, 5, 3, 6, 4]), 5) self.assertEqual(max_profit_optimized([7, 6, 4, 3, 1]), 0) class TestClimbingStairs(unittest.TestCase): def test_climb_stairs(self): self.assertEqual(climb_stairs(2), 2) self.assertEqual(climb_stairs(10), 89) def test_climb_stairs_optimized(self): self.assertEqual(climb_stairs_optimized(2), 2) self.assertEqual(climb_stairs_optimized(10), 89) class TestCoinChange(unittest.TestCase): def test_count(self): self.assertEqual(count([1, 2, 3], 4), 4) self.assertEqual(count([2, 5, 3, 6], 10), 5) class TestCombinationSum(unittest.TestCase): def test_combination_sum_topdown(self): self.assertEqual(combination_sum_topdown([1, 2, 3], 4), 7) def test_combination_sum_bottom_up(self): self.assertEqual(combination_sum_bottom_up([1, 2, 3], 4), 7) class TestEditDistance(unittest.TestCase): def test_edit_distance(self): self.assertEqual(edit_distance('food', 'money'), 4) self.assertEqual(edit_distance('horse', 'ros'), 3) class TestEggDrop(unittest.TestCase): def test_egg_drop(self): self.assertEqual(egg_drop(1, 2), 2) self.assertEqual(egg_drop(2, 6), 3) self.assertEqual(egg_drop(3, 14), 4) class TestFib(unittest.TestCase): def test_fib_recursive(self): self.assertEqual(fib_recursive(10), 55) self.assertEqual(fib_recursive(30), 832040) def test_fib_list(self): self.assertEqual(fib_list(10), 55) self.assertEqual(fib_list(30), 832040) def test_fib_iter(self): self.assertEqual(fib_iter(10), 55) self.assertEqual(fib_iter(30), 832040) class TestHosoyaTriangle(unittest.TestCase): """[summary] Test for the file hosoya_triangle Arguments: unittest {[type]} -- [description] """ def test_hosoya(self): self.assertEqual([1], hosoya_testing(1)) self.assertEqual([1, 1, 1, 2, 1, 2, 3, 2, 2, 3, 5, 3, 4, 3, 5, 8, 5, 6, 6, 5, 8], hosoya_testing(6)) self.assertEqual([1, 1, 1, 2, 1, 2, 3, 2, 2, 3, 5, 3, 4, 3, 5, 8, 5, 6, 6, 5, 8, 13, 8, 10, 9, 10, 8, 13, 21, 13, 16, 15, 15, 16, 13, 21, 34, 21, 26, 24, 25, 24, 26, 21, 34, 55, 34, 42, 39, 40, 40, 39, 42, 34, 55], hosoya_testing(10)) class TestHouseRobber(unittest.TestCase): def test_house_robber(self): self.assertEqual(44, house_robber([1, 2, 16, 3, 15, 3, 12, 1])) class TestJobScheduling(unittest.TestCase): def test_job_scheduling(self): job1, job2 = Job(1, 3, 2), Job(2, 3, 4) self.assertEqual(4, schedule([job1, job2])) class TestKnapsack(unittest.TestCase): def test_get_maximum_value(self): item1, item2, item3 = Item(60, 10), Item(100, 20), Item(120, 30) self.assertEqual(220, get_maximum_value([item1, item2, item3], 50)) item1, item2, item3, item4 = Item(60, 5), Item(50, 3), Item(70, 4), Item(30, 2) self.assertEqual(80, get_maximum_value([item1, item2, item3, item4], 5)) class TestLongestIncreasingSubsequence(unittest.TestCase): def test_longest_increasing_subsequence(self): sequence = [1, 101, 10, 2, 3, 100, 4, 6, 2] self.assertEqual(5, longest_increasing_subsequence(sequence)) class TestLongestIncreasingSubsequenceOptimized(unittest.TestCase): def test_longest_increasing_subsequence_optimized(self): sequence = [1, 101, 10, 2, 3, 100, 4, 6, 2] self.assertEqual(5, longest_increasing_subsequence(sequence)) class TestLongestIncreasingSubsequenceOptimized2(unittest.TestCase): def test_longest_increasing_subsequence_optimized2(self): sequence = [1, 101, 10, 2, 3, 100, 4, 6, 2] self.assertEqual(5, longest_increasing_subsequence(sequence)) class TestIntDivide(unittest.TestCase): def test_int_divide(self): self.assertEqual(5, int_divide(4)) self.assertEqual(42, int_divide(10)) self.assertEqual(204226, int_divide(50)) class Test_dp_K_Factor(unittest.TestCase): def test_kfactor(self): # Test 1 n1 = 4 k1 = 1 self.assertEqual(find_k_factor(n1, k1), 1) # Test 2 n2 = 7 k2 = 1 self.assertEqual(find_k_factor(n2, k2), 70302) # Test 3 n3 = 10 k3 = 2 self.assertEqual(find_k_factor(n3, k3), 74357) # Test 4 n4 = 8 k4 = 2 self.assertEqual(find_k_factor(n4, k4), 53) # Test 5 n5 = 9 k5 = 1 self.assertEqual(find_k_factor(n5, k5), 71284044) class TestPlantingTrees(unittest.TestCase): def test_simple(self): # arrange trees = [0, 1, 10, 10] L = 10 W = 1 # act res = planting_trees(trees, L, W) # assert self.assertEqual(res, 2.414213562373095) def test_simple2(self): # arrange trees = [0, 3, 5, 5, 6, 9] L = 10 W = 1 # act res = planting_trees(trees, L, W) # assert self.assertEqual(res, 9.28538328578604) class TestRegexMatching(unittest.TestCase): def test_none_0(self): s = "" p = "" self.assertTrue(regex_matching.is_match(s, p)) def test_none_1(self): s = "" p = "a" self.assertFalse(regex_matching.is_match(s, p)) def test_no_symbol_equal(self): s = "abcd" p = "abcd" self.assertTrue(regex_matching.is_match(s, p)) def test_no_symbol_not_equal_0(self): s = "abcd" p = "efgh" self.assertFalse(regex_matching.is_match(s, p)) def test_no_symbol_not_equal_1(self): s = "ab" p = "abb" self.assertFalse(regex_matching.is_match(s, p)) def test_symbol_0(self): s = "" p = "a*" self.assertTrue(regex_matching.is_match(s, p)) def test_symbol_1(self): s = "a" p = "ab*" self.assertTrue(regex_matching.is_match(s, p)) def test_symbol_2(self): # E.g. # s a b b # p 1 0 0 0 # a 0 1 0 0 # b 0 0 1 0 # * 0 1 1 1 s = "abb" p = "ab*" self.assertTrue(regex_matching.is_match(s, p)) if __name__ == '__main__': unittest.main()
Test for the file tarjan.py Arguments: unittest type description Graph from https:en.wikipedia.orgwikiFile:Scc.png Graph from https:en.wikipedia.orgwikiTarjan27sstronglyconnectedcomponentsalgorithmmediaFile:Tarjan27sAlgorithmAnimation.gif Test for the file maximumflow.py Arguments: unittest type description Test for the file def maximumflowbfs.py Arguments: unittest type description Test for the file def maximumflowdfs.py Arguments: unittest type description Class for testing different cases for connected components in graph Test Function that test the different cases of count connected components 20 15 3 4 output 3 adjacency list representation of graph input : output : 0 input : 0 2 3 4 output : 4
from algorithms.graph import Tarjan from algorithms.graph import check_bipartite from algorithms.graph.dijkstra import Dijkstra from algorithms.graph import ford_fulkerson from algorithms.graph import edmonds_karp from algorithms.graph import dinic from algorithms.graph import maximum_flow_bfs from algorithms.graph import maximum_flow_dfs from algorithms.graph import all_pairs_shortest_path from algorithms.graph import bellman_ford from algorithms.graph import count_connected_number_of_component from algorithms.graph import prims_minimum_spanning from algorithms.graph import check_digraph_strongly_connected from algorithms.graph import cycle_detection from algorithms.graph import find_path from algorithms.graph import path_between_two_vertices_in_digraph import unittest class TestTarjan(unittest.TestCase): """ Test for the file tarjan.py Arguments: unittest {[type]} -- [description] """ def test_tarjan_example_1(self): # Graph from https://en.wikipedia.org/wiki/File:Scc.png example = { 'A': ['B'], 'B': ['C', 'E', 'F'], 'C': ['D', 'G'], 'D': ['C', 'H'], 'E': ['A', 'F'], 'F': ['G'], 'G': ['F'], 'H': ['D', 'G'] } g = Tarjan(example) self.assertEqual(g.sccs, [['F', 'G'], ['C', 'D', 'H'], ['A', 'B', 'E']]) def test_tarjan_example_2(self): # Graph from https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm#/media/File:Tarjan%27s_Algorithm_Animation.gif example = { 'A': ['E'], 'B': ['A'], 'C': ['B', 'D'], 'D': ['C'], 'E': ['B'], 'F': ['B', 'E', 'G'], 'G': ['F', 'C'], 'H': ['G', 'H', 'D'] } g = Tarjan(example) self.assertEqual(g.sccs, [['A', 'B', 'E'], ['C', 'D'], ['F', 'G'], ['H']]) class TestCheckBipartite(unittest.TestCase): def test_check_bipartite(self): adj_list_1 = [[0, 0, 1], [0, 0, 1], [1, 1, 0]] self.assertEqual(True, check_bipartite(adj_list_1)) adj_list_2 = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]] self.assertEqual(True, check_bipartite(adj_list_2)) adj_list_3 = [[0, 1, 0, 0], [1, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0]] self.assertEqual(False, check_bipartite(adj_list_3)) class TestDijkstra(unittest.TestCase): def test_dijkstra(self): g = Dijkstra(9) g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], [4, 0, 8, 0, 0, 0, 0, 11, 0], [0, 8, 0, 7, 0, 4, 0, 0, 2], [0, 0, 7, 0, 9, 14, 0, 0, 0], [0, 0, 0, 9, 0, 10, 0, 0, 0], [0, 0, 4, 14, 10, 0, 2, 0, 0], [0, 0, 0, 0, 0, 2, 0, 1, 6], [8, 11, 0, 0, 0, 0, 1, 0, 7], [0, 0, 2, 0, 0, 0, 6, 7, 0]] self.assertEqual(g.dijkstra(0), [0, 4, 12, 19, 21, 11, 9, 8, 14]) class TestMaximumFlow(unittest.TestCase): """ Test for the file maximum_flow.py Arguments: unittest {[type]} -- [description] """ def test_ford_fulkerson(self): capacity = [ [0, 10, 10, 0, 0, 0, 0], [0, 0, 2, 0, 4, 8, 0], [0, 0, 0, 0, 0, 9, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 10], [0, 0, 0, 0, 6, 0, 10], [0, 0, 0, 0, 0, 0, 0] ] self.assertEqual(19, ford_fulkerson(capacity, 0, 6)) def test_edmonds_karp(self): capacity = [ [0, 10, 10, 0, 0, 0, 0], [0, 0, 2, 0, 4, 8, 0], [0, 0, 0, 0, 0, 9, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 10], [0, 0, 0, 0, 6, 0, 10], [0, 0, 0, 0, 0, 0, 0] ] self.assertEqual(19, edmonds_karp(capacity, 0, 6)) def dinic(self): capacity = [ [0, 10, 10, 0, 0, 0, 0], [0, 0, 2, 0, 4, 8, 0], [0, 0, 0, 0, 0, 9, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 10], [0, 0, 0, 0, 6, 0, 10], [0, 0, 0, 0, 0, 0, 0] ] self.assertEqual(19, dinic(capacity, 0, 6)) class TestMaximum_Flow_Bfs(unittest.TestCase): """ Test for the file def maximum_flow_bfs.py Arguments: unittest {[type]} -- [description] """ def test_maximum_flow_bfs(self): graph = [ [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] ] maximum_flow = maximum_flow_bfs(graph) self.assertEqual(maximum_flow, 23) class TestMaximum_Flow_Dfs(unittest.TestCase): """ Test for the file def maximum_flow_dfs.py Arguments: unittest {[type]} -- [description] """ def test_maximum_flow_dfs(self): graph = [ [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] ] maximum_flow = maximum_flow_dfs(graph) self.assertEqual(maximum_flow, 23) class TestAll_Pairs_Shortest_Path(unittest.TestCase): def test_all_pairs_shortest_path(self): graph = [[0, 0.1, 0.101, 0.142, 0.277], [0.465, 0, 0.191, 0.192, 0.587], [0.245, 0.554, 0, 0.333, 0.931], [1.032, 0.668, 0.656, 0, 0.151], [0.867, 0.119, 0.352, 0.398, 0]] result = all_pairs_shortest_path(graph) self.assertEqual(result, [ [0, 0.1, 0.101, 0.142, 0.277], [0.436, 0, 0.191, 0.192, 0.34299999999999997], [0.245, 0.345, 0, 0.333, 0.484], [0.706, 0.27, 0.46099999999999997, 0, 0.151], [0.5549999999999999, 0.119, 0.31, 0.311, 0], ]) class TestBellmanFord(unittest.TestCase): def test_bellman_ford(self): graph1 = { 'a': {'b': 6, 'e': 7}, 'b': {'c': 5, 'd': -4, 'e': 8}, 'c': {'b': -2}, 'd': {'a': 2, 'c': 7}, 'e': {'b': -3} } self.assertEqual(True, bellman_ford(graph1, 'a')) graph2 = { 'a': {'d': 3, 'e': 4}, 'b': {'a': 7, 'e': 2}, 'c': {'a': 12, 'd': 9, 'e': 11}, 'd': {'c': 5, 'e': 11}, 'e': {'a': 7, 'b': 5, 'd': 1} } self.assertEqual(True, bellman_ford(graph2, 'a')) class TestConnectedComponentInGraph(unittest.TestCase): """ Class for testing different cases for connected components in graph """ def test_count_connected_components(self): """ Test Function that test the different cases of count connected components 2----------0 1--------5 3 | | 4 output = 3 """ expected_result = 3 # adjacency list representation of graph l = [[2], [5], [0,4], [], [2], [1]] size = 5 result = count_connected_number_of_component.count_components(l, size) self.assertEqual(result, expected_result) def test_connected_components_with_empty_graph(self): """ input : output : 0 """ l = [[]] expected_result = 0 size = 0 result = count_connected_number_of_component.count_components(l, size) self.assertEqual(result, expected_result) def test_connected_components_without_edges_graph(self): """ input : 0 2 3 4 output : 4 """ l = [[0], [], [2], [3], [4]] size = 4 expected_result = 4 result = count_connected_number_of_component.count_components(l, size) self.assertEqual(result, expected_result) class PrimsMinimumSpanning(unittest.TestCase): def test_prim_spanning(self): graph1 = { 1: [[3, 2], [8, 3]], 2: [[3, 1], [5, 4]], 3: [[8, 1], [2, 4], [4, 5]], 4: [[5, 2], [2, 3], [6, 5]], 5: [[4, 3], [6, 4]] } self.assertEqual(14, prims_minimum_spanning(graph1)) graph2 = { 1: [[7, 2], [6, 4]], 2: [[7, 1], [9, 4], [6, 3]], 3: [[8, 4], [6, 2]], 4: [[6, 1], [9, 2], [8, 3]] } self.assertEqual(19, prims_minimum_spanning(graph2)) class TestDigraphStronglyConnected(unittest.TestCase): def test_digraph_strongly_connected(self): g1 = check_digraph_strongly_connected.Graph(5) g1.add_edge(0, 1) g1.add_edge(1, 2) g1.add_edge(2, 3) g1.add_edge(3, 0) g1.add_edge(2, 4) g1.add_edge(4, 2) self.assertTrue(g1.is_strongly_connected()) g2 = check_digraph_strongly_connected.Graph(4) g2.add_edge(0, 1) g2.add_edge(1, 2) g2.add_edge(2, 3) self.assertFalse(g2.is_strongly_connected()) class TestCycleDetection(unittest.TestCase): def test_cycle_detection_with_cycle(self): graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['F'], 'D': ['E', 'F'], 'E': ['B'], 'F': []} self.assertTrue(cycle_detection.contains_cycle(graph)) def test_cycle_detection_with_no_cycle(self): graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': ['E'], 'E': [], 'F': []} self.assertFalse(cycle_detection.contains_cycle(graph)) class TestFindPath(unittest.TestCase): def test_find_all_paths(self): graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D', 'F'], 'D': ['C'], 'E': ['F'], 'F': ['C']} paths = find_path.find_all_path(graph, 'A', 'F') print(paths) self.assertEqual(sorted(paths), sorted([ ['A', 'C', 'F'], ['A', 'B', 'C', 'F'], ['A', 'B', 'D', 'C', 'F'], ])) class TestPathBetweenTwoVertices(unittest.TestCase): def test_node_is_reachable(self): g = path_between_two_vertices_in_digraph.Graph(4) g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) self.assertTrue(g.is_reachable(1, 3)) self.assertFalse(g.is_reachable(3, 1))
Test suite for the binaryheap data structures Before insert 2: 0, 4, 50, 7, 55, 90, 87 After insert: 0, 2, 50, 4, 55, 90, 87, 7 Before removemin : 0, 4, 50, 7, 55, 90, 87 After removemin: 7, 50, 87, 55, 90 Test return value Expect output
from algorithms.heap import ( BinaryHeap, get_skyline, max_sliding_window, k_closest ) import unittest class TestBinaryHeap(unittest.TestCase): """ Test suite for the binary_heap data structures """ def setUp(self): self.min_heap = BinaryHeap() self.min_heap.insert(4) self.min_heap.insert(50) self.min_heap.insert(7) self.min_heap.insert(55) self.min_heap.insert(90) self.min_heap.insert(87) def test_insert(self): # Before insert 2: [0, 4, 50, 7, 55, 90, 87] # After insert: [0, 2, 50, 4, 55, 90, 87, 7] self.min_heap.insert(2) self.assertEqual([0, 2, 50, 4, 55, 90, 87, 7], self.min_heap.heap) self.assertEqual(7, self.min_heap.current_size) def test_remove_min(self): ret = self.min_heap.remove_min() # Before remove_min : [0, 4, 50, 7, 55, 90, 87] # After remove_min: [7, 50, 87, 55, 90] # Test return value self.assertEqual(4, ret) self.assertEqual([0, 7, 50, 87, 55, 90], self.min_heap.heap) self.assertEqual(5, self.min_heap.current_size) class TestSuite(unittest.TestCase): def test_get_skyline(self): buildings = [[2, 9, 10], [3, 7, 15], [5, 12, 12], [15, 20, 10], [19, 24, 8]] # Expect output output = [[2, 10], [3, 15], [7, 12], [12, 0], [15, 10], [20, 8], [24, 0]] self.assertEqual(output, get_skyline(buildings)) def test_max_sliding_window(self): nums = [1, 3, -1, -3, 5, 3, 6, 7] self.assertEqual([3, 3, 5, 5, 6, 7], max_sliding_window(nums, 3)) def test_k_closest_points(self): points = [(1, 0), (2, 3), (5, 2), (1, 1), (2, 8), (10, 2), (-1, 0), (-2, -2)] self.assertEqual([(-1, 0), (1, 0)], k_closest(points, 2)) self.assertEqual([(1, 1), (-1, 0), (1, 0)], k_closest(points, 3)) self.assertEqual([(-2, -2), (1, 1), (1, 0), (-1, 0)], k_closest(points, 4)) self.assertEqual([(10, 2), (2, 8), (5, 2), (-2, -2), (2, 3), (1, 0), (-1, 0), (1, 1)], k_closest(points, 8)) if __name__ == "__main__": unittest.main()
Test for the Iterative Segment Tree data structure Test all possible segments in the tree :param arr: array to test :param fnc: function of the segment tpree Test all possible segments in the tree with updates :param arr: array to test :param fnc: function of the segment tree :param upd: updates to test
from algorithms.tree.segment_tree.iterative_segment_tree import SegmentTree from functools import reduce import unittest def gcd(a, b): if b == 0: return a return gcd(b, a % b) class TestSegmentTree(unittest.TestCase): """ Test for the Iterative Segment Tree data structure """ def test_segment_tree_creation(self): arr = [2, 4, 3, 6, 8, 9, 3] max_segment_tree = SegmentTree(arr, max) min_segment_tree = SegmentTree(arr, min) sum_segment_tree = SegmentTree(arr, lambda a, b: a + b) gcd_segment_tree = SegmentTree(arr, gcd) self.assertEqual(max_segment_tree.tree, [None, 9, 8, 9, 4, 8, 9, 2, 4, 3, 6, 8, 9, 3]) self.assertEqual(min_segment_tree.tree, [None, 2, 3, 2, 3, 6, 3, 2, 4, 3, 6, 8, 9, 3]) self.assertEqual(sum_segment_tree.tree, [None, 35, 21, 14, 7, 14, 12, 2, 4, 3, 6, 8, 9, 3]) self.assertEqual(gcd_segment_tree.tree, [None, 1, 1, 1, 1, 2, 3, 2, 4, 3, 6, 8, 9, 3]) def test_max_segment_tree(self): arr = [-1, 1, 10, 2, 9, -3, 8, 4, 7, 5, 6, 0] self.__test_all_segments(arr, max) def test_min_segment_tree(self): arr = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] self.__test_all_segments(arr, min) def test_sum_segment_tree(self): arr = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6, -11, -12] self.__test_all_segments(arr, lambda a, b: a + b) def test_gcd_segment_tree(self): arr = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6, 11, 12, 14] self.__test_all_segments(arr, gcd) def test_max_segment_tree_with_updates(self): arr = [-1, 1, 10, 2, 9, -3, 8, 4, 7, 5, 6, 0] updates = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10, 10: 11, 11: 12} self.__test_all_segments_with_updates(arr, max, updates) def test_min_segment_tree_with_updates(self): arr = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] updates = {0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1} self.__test_all_segments_with_updates(arr, min, updates) def test_sum_segment_tree_with_updates(self): arr = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6, -11, -12] updates = {0: 12, 1: 11, 2: 10, 3: 9, 4: 8, 5: 7, 6: 6, 7: 5, 8: 4, 9: 3, 10: 2, 11: 1} self.__test_all_segments_with_updates(arr, lambda a, b: a + b, updates) def test_gcd_segment_tree_with_updates(self): arr = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6, 11, 12, 14] updates = {0: 4, 1: 2, 2: 3, 3: 9, 4: 21, 5: 7, 6: 4, 7: 4, 8: 2, 9: 5, 10: 17, 11: 12, 12: 3} self.__test_all_segments_with_updates(arr, gcd, updates) def __test_all_segments(self, arr, fnc): """ Test all possible segments in the tree :param arr: array to test :param fnc: function of the segment tpree """ segment_tree = SegmentTree(arr, fnc) self.__test_segments_helper(segment_tree, fnc, arr) def __test_all_segments_with_updates(self, arr, fnc, upd): """ Test all possible segments in the tree with updates :param arr: array to test :param fnc: function of the segment tree :param upd: updates to test """ segment_tree = SegmentTree(arr, fnc) for index, value in upd.items(): arr[index] = value segment_tree.update(index, value) self.__test_segments_helper(segment_tree, fnc, arr) def __test_segments_helper(self, seg_tree, fnc, arr): for i in range(0, len(arr)): for j in range(i, len(arr)): range_value = reduce(fnc, arr[i:j + 1]) self.assertEqual(seg_tree.query(i, j), range_value)
Convert from linked list Node to list for testing list test for palindrome head 2 2 2 4 9 head 1 2 8 4 6 Test case: middle case. Expect output: 0 4 Test case: taking out the front node Expect output: 2 3 4 Test case: removing all the nodes Expect output : 2 1 4 3 Given 12345NULL K 2. Expect output: 45123NULL. create linked list A B C D E C create linked list 1 2 3 4 Input: head1:124, head2: 134 Output: 112344 Test recursive
import unittest from algorithms.linkedlist import ( reverse_list, reverse_list_recursive, is_sorted, remove_range, swap_pairs, rotate_right, is_cyclic, merge_two_list, merge_two_list_recur, is_palindrome, is_palindrome_stack, is_palindrome_dict, RandomListNode, copy_random_pointer_v1, copy_random_pointer_v2 ) class Node(object): def __init__(self, x): self.val = x self.next = None # Convert from linked list Node to list for testing def convert(head): ret = [] if head: current = head while current: ret.append(current.val) current = current.next return ret class TestSuite(unittest.TestCase): def setUp(self): # list test for palindrome self.l = Node('A') self.l.next = Node('B') self.l.next.next = Node('C') self.l.next.next.next = Node('B') self.l.next.next.next.next = Node('A') self.l1 = Node('A') self.l1.next = Node('B') self.l1.next.next = Node('C') self.l1.next.next.next = Node('B') def test_reverse_list(self): head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) self.assertEqual([4, 3, 2, 1], convert(reverse_list(head))) head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) self.assertEqual([4, 3, 2, 1], convert(reverse_list_recursive(head))) def test_is_sorted(self): head = Node(-2) head.next = Node(2) head.next.next = Node(2) head.next.next.next = Node(4) head.next.next.next.next = Node(9) # head -> -2 -> 2 -> 2 -> 4 -> 9 self.assertTrue(is_sorted(head)) head = Node(1) head.next = Node(2) head.next.next = Node(8) head.next.next.next = Node(4) head.next.next.next.next = Node(6) # head -> 1 -> 2 -> 8 -> 4 -> 6 self.assertFalse(is_sorted(head)) def test_remove_range(self): # Test case: middle case. head = Node(0) head.next = Node(1) head.next.next = Node(2) head.next.next.next = Node(3) head.next.next.next.next = Node(4) # Expect output: 0 4 self.assertEqual([0, 4], convert(remove_range(head, 1, 3))) # Test case: taking out the front node head = Node(0) head.next = Node(1) head.next.next = Node(2) head.next.next.next = Node(3) head.next.next.next.next = Node(4) # Expect output: 2 3 4 self.assertEqual([2, 3, 4], convert(remove_range(head, 0, 1))) # Test case: removing all the nodes head = Node(0) head.next = Node(1) head.next.next = Node(2) head.next.next.next = Node(3) head.next.next.next.next = Node(4) self.assertEqual([], convert(remove_range(head, 0, 7))) def test_swap_in_pairs(self): head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) # Expect output : 2 --> 1 --> 4 --> 3 self.assertEqual([2, 1, 4, 3], convert(swap_pairs(head))) def test_rotate_right(self): # Given 1->2->3->4->5->NULL head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) # K = 2. Expect output: 4->5->1->2->3->NULL. self.assertEqual([4, 5, 1, 2, 3], convert(rotate_right(head, 2))) def test_is_cyclic(self): # create linked list => A -> B -> C -> D -> E -> C head = Node('A') head.next = Node('B') curr = head.next cyclic_node = Node('C') curr.next = cyclic_node curr = curr.next curr.next = Node('D') curr = curr.next curr.next = Node('E') curr = curr.next curr.next = cyclic_node self.assertTrue(is_cyclic(head)) # create linked list 1 -> 2 -> 3 -> 4 head = Node(1) curr = head for i in range(2, 6): curr.next = Node(i) curr = curr.next self.assertFalse(is_cyclic(head)) def test_merge_two_list(self): """ Input: head1:1->2->4, head2: 1->3->4 Output: 1->1->2->3->4->4 """ head1 = Node(1) head1.next = Node(2) head1.next.next = Node(4) head2 = Node(1) head2.next = Node(3) head2.next.next = Node(4) self.assertEqual([1, 1, 2, 3, 4, 4], convert(merge_two_list(head1, head2))) # Test recursive head1 = Node(1) head1.next = Node(2) head1.next.next = Node(4) head2 = Node(1) head2.next = Node(3) head2.next.next = Node(4) self.assertEqual([1, 1, 2, 3, 4, 4], convert(merge_two_list_recur(head1, head2))) def test_is_palindrome(self): self.assertTrue(is_palindrome(self.l)) self.assertFalse(is_palindrome(self.l1)) def test_is_palindrome_stack(self): self.assertTrue(is_palindrome_stack(self.l)) self.assertFalse(is_palindrome_stack(self.l1)) def test_is_palindrome_dict(self): self.assertTrue(is_palindrome_dict(self.l)) self.assertFalse(is_palindrome_dict(self.l1)) def test_solution_0(self): self._init_random_list_nodes() result = copy_random_pointer_v1(self.random_list_node1) self._assert_is_a_copy(result) def test_solution_1(self): self._init_random_list_nodes() result = copy_random_pointer_v2(self.random_list_node1) self._assert_is_a_copy(result) def _assert_is_a_copy(self, result): self.assertEqual(5, result.next.next.next.next.label) self.assertEqual(4, result.next.next.next.label) self.assertEqual(3, result.next.next.label) self.assertEqual(2, result.next.label) self.assertEqual(1, result.label) self.assertEqual(3, result.next.next.next.next.random.label) self.assertIsNone(result.next.next.next.random) self.assertEqual(2, result.next.next.random.label) self.assertEqual(5, result.next.random.label) self.assertEqual(4, result.random.label) def _init_random_list_nodes(self): self.random_list_node1 = RandomListNode(1) random_list_node2 = RandomListNode(2) random_list_node3 = RandomListNode(3) random_list_node4 = RandomListNode(4) random_list_node5 = RandomListNode(5) self.random_list_node1.next, self.random_list_node1.random = random_list_node2, random_list_node4 random_list_node2.next, random_list_node2.random = random_list_node3, random_list_node5 random_list_node3.next, random_list_node3.random = random_list_node4, random_list_node2 random_list_node4.next = random_list_node5 random_list_node5.random = random_list_node3 if __name__ == "__main__": unittest.main()
and does not search forever
from algorithms.map import ( HashTable, ResizableHashTable, SeparateChainingHashTable, word_pattern, is_isomorphic, is_anagram, longest_palindromic_subsequence, ) import unittest class TestHashTable(unittest.TestCase): def test_one_entry(self): m = HashTable(10) m.put(1, '1') self.assertEqual('1', m.get(1)) def test_add_entry_bigger_than_table_size(self): m = HashTable(10) m.put(11, '1') self.assertEqual('1', m.get(11)) def test_get_none_if_key_missing_and_hash_collision(self): m = HashTable(10) m.put(1, '1') self.assertEqual(None, m.get(11)) def test_two_entries_with_same_hash(self): m = HashTable(10) m.put(1, '1') m.put(11, '11') self.assertEqual('1', m.get(1)) self.assertEqual('11', m.get(11)) def test_get_on_full_table_does_halts(self): # and does not search forever m = HashTable(10) for i in range(10, 20): m.put(i, i) self.assertEqual(None, m.get(1)) def test_delete_key(self): m = HashTable(10) for i in range(5): m.put(i, i**2) m.del_(1) self.assertEqual(None, m.get(1)) self.assertEqual(4, m.get(2)) def test_delete_key_and_reassign(self): m = HashTable(10) m.put(1, 1) del m[1] m.put(1, 2) self.assertEqual(2, m.get(1)) def test_assigning_to_full_table_throws_error(self): m = HashTable(3) m.put(1, 1) m.put(2, 2) m.put(3, 3) with self.assertRaises(ValueError): m.put(4, 4) def test_len_trivial(self): m = HashTable(10) self.assertEqual(0, len(m)) for i in range(10): m.put(i, i) self.assertEqual(i + 1, len(m)) def test_len_after_deletions(self): m = HashTable(10) m.put(1, 1) self.assertEqual(1, len(m)) m.del_(1) self.assertEqual(0, len(m)) m.put(11, 42) self.assertEqual(1, len(m)) def test_resizable_hash_table(self): m = ResizableHashTable() self.assertEqual(ResizableHashTable.MIN_SIZE, m.size) for i in range(ResizableHashTable.MIN_SIZE): m.put(i, 'foo') self.assertEqual(ResizableHashTable.MIN_SIZE * 2, m.size) self.assertEqual('foo', m.get(1)) self.assertEqual('foo', m.get(3)) self.assertEqual('foo', m.get(ResizableHashTable.MIN_SIZE - 1)) def test_fill_up_the_limit(self): m = HashTable(10) for i in range(10): m.put(i, i**2) for i in range(10): self.assertEqual(i**2, m.get(i)) class TestSeparateChainingHashTable(unittest.TestCase): def test_one_entry(self): m = SeparateChainingHashTable(10) m.put(1, '1') self.assertEqual('1', m.get(1)) def test_two_entries_with_same_hash(self): m = SeparateChainingHashTable(10) m.put(1, '1') m.put(11, '11') self.assertEqual('1', m.get(1)) self.assertEqual('11', m.get(11)) def test_len_trivial(self): m = SeparateChainingHashTable(10) self.assertEqual(0, len(m)) for i in range(10): m.put(i, i) self.assertEqual(i + 1, len(m)) def test_len_after_deletions(self): m = SeparateChainingHashTable(10) m.put(1, 1) self.assertEqual(1, len(m)) m.del_(1) self.assertEqual(0, len(m)) m.put(11, 42) self.assertEqual(1, len(m)) def test_delete_key(self): m = SeparateChainingHashTable(10) for i in range(5): m.put(i, i**2) m.del_(1) self.assertEqual(None, m.get(1)) self.assertEqual(4, m.get(2)) def test_delete_key_and_reassign(self): m = SeparateChainingHashTable(10) m.put(1, 1) del m[1] m.put(1, 2) self.assertEqual(2, m.get(1)) def test_add_entry_bigger_than_table_size(self): m = SeparateChainingHashTable(10) m.put(11, '1') self.assertEqual('1', m.get(11)) def test_get_none_if_key_missing_and_hash_collision(self): m = SeparateChainingHashTable(10) m.put(1, '1') self.assertEqual(None, m.get(11)) class TestWordPattern(unittest.TestCase): def test_word_pattern(self): self.assertTrue(word_pattern("abba", "dog cat cat dog")) self.assertFalse(word_pattern("abba", "dog cat cat fish")) self.assertFalse(word_pattern("abba", "dog dog dog dog")) self.assertFalse(word_pattern("aaaa", "dog cat cat dog")) class TestIsSomorphic(unittest.TestCase): def test_is_isomorphic(self): self.assertTrue(is_isomorphic("egg", "add")) self.assertFalse(is_isomorphic("foo", "bar")) self.assertTrue(is_isomorphic("paper", "title")) class TestLongestPalindromicSubsequence(unittest.TestCase): def test_longest_palindromic_subsequence_is_correct(self): self.assertEqual(3, longest_palindromic_subsequence('BBABCBCAB')) self.assertEqual(4, longest_palindromic_subsequence('abbaeae')) self.assertEqual(7, longest_palindromic_subsequence('babbbababaa')) self.assertEqual(4, longest_palindromic_subsequence('daccandeeja')) def test_longest_palindromic_subsequence_is_incorrect(self): self.assertNotEqual(4, longest_palindromic_subsequence('BBABCBCAB')) self.assertNotEqual(5, longest_palindromic_subsequence('abbaeae')) self.assertNotEqual(2, longest_palindromic_subsequence('babbbababaa')) self.assertNotEqual(1, longest_palindromic_subsequence('daccandeeja')) class TestIsAnagram(unittest.TestCase): def test_is_anagram(self): self.assertTrue(is_anagram("anagram", "nagaram")) self.assertFalse(is_anagram("rat", "car")) if __name__ == "__main__": unittest.main()
Test for the file power.py Arguments: unittest type description Test for the file baseconversion.py Arguments: unittest type description Test for the file decimaltobinaryip.py Arguments: unittest type description summary Test for the file eulertotient.py Arguments: unittest type description summary Test for the file extendedgcd.py Arguments: unittest type description summary Test for the file gcd.py Arguments: unittest type description summary Test for the file generatestrobogrammatic.py Arguments: unittest type description summary Test for the file isstrobogrammatic.py Arguments: unittest type description summary Test for the file modularExponential.py Arguments: unittest type description checks if x xinv 1 mod m summary Test for the file modularExponential.py Arguments: unittest type description summary Test for the file nextperfectsquare.py Arguments: unittest type description summary Test for the file primessieveoferatosthenes.py Arguments: unittest type description summary Test for the file primetest.py Arguments: unittest type description checks all prime numbers between 2 up to 100. Between 2 up to 100 exists 25 prime numbers! summary Test for the file pythagoras.py Arguments: unittest type description summary Test for the file rabinmiller.py Arguments: unittest type description summary Test for the file rsa.py Arguments: unittest type description def testkeygeneratorself: this test takes a while! for i in range100: printstep 0.formati n, e, d generatekey26 data 2 en encryptdata, e, n dec decrypten, d, n self.assertEqualdata,dec summary Test for the file combination.py Arguments: unittest type description summary Test for the file factorial.py Arguments: unittest type description summary Test for the file hailstone.py Arguments: unittest type description summary Test for the file cosinesimilarity.py Arguments: unittest type description summary Test for the file findprimitiverootsimple.py Arguments: unittest type description summary Test for the file findordersimple.py Arguments: unittest type description summary Test for the file krishnamurthynumber.py Arguments: unittest type description summary Test for the file findordersimple.py Arguments: unittest type description summary Test for the file diffiehellmankeyexchange.py Arguments: unittest type description summary Test for the file numdigits.py Arguments: unittest type description summary Test for the file numperfectsquares.py Arguments: unittest type description Example which should give the answer 143 which is the smallest possible x that solves the system of equations Example which should give the answer 3383 which is the smallest possible x that solves the system of equations There should be an exception when all numbers in num are not pairwise coprime summary Test for the file fft.py Arguments: unittest type description abscomplex returns the magnitude
from algorithms.maths import ( power, power_recur, int_to_base, base_to_int, decimal_to_binary_ip, euler_totient, extended_gcd, factorial, factorial_recur, gcd, lcm, trailing_zero, gcd_bit, gen_strobogrammatic, strobogrammatic_in_range, is_strobogrammatic, is_strobogrammatic2, modular_inverse, modular_exponential, find_next_square, find_next_square2, prime_check, get_primes, pythagoras, is_prime, encrypt, decrypt, combination, combination_memo, hailstone, cosine_similarity, magic_number, find_order, find_primitive_root, num_digits, diffie_hellman_key_exchange, krishnamurthy_number, num_perfect_squares, chinese_remainder_theorem, fft ) import unittest import pytest class TestPower(unittest.TestCase): """ Test for the file power.py Arguments: unittest {[type]} -- [description] """ def test_power(self): self.assertEqual(8, power(2, 3)) self.assertEqual(1, power(5, 0)) self.assertEqual(0, power(10, 3, 5)) self.assertEqual(280380, power(2265, 1664, 465465)) def test_power_recur(self): self.assertEqual(8, power_recur(2, 3)) self.assertEqual(1, power_recur(5, 0)) self.assertEqual(0, power_recur(10, 3, 5)) self.assertEqual(280380, power_recur(2265, 1664, 465465)) class TestBaseConversion(unittest.TestCase): """ Test for the file base_conversion.py Arguments: unittest {[type]} -- [description] """ def test_int_to_base(self): self.assertEqual("101", int_to_base(5, 2)) self.assertEqual("0", int_to_base(0, 2)) self.assertEqual("FF", int_to_base(255, 16)) def test_base_to_int(self): self.assertEqual(5, base_to_int("101", 2)) self.assertEqual(0, base_to_int("0", 2)) self.assertEqual(255, base_to_int("FF", 16)) class TestDecimalToBinaryIP(unittest.TestCase): """ Test for the file decimal_to_binary_ip.py Arguments: unittest {[type]} -- [description] """ def test_decimal_to_binary_ip(self): self.assertEqual("00000000.00000000.00000000.00000000", decimal_to_binary_ip("0.0.0.0")) self.assertEqual("11111111.11111111.11111111.11111111", decimal_to_binary_ip("255.255.255.255")) self.assertEqual("11000000.10101000.00000000.00000001", decimal_to_binary_ip("192.168.0.1")) class TestEulerTotient(unittest.TestCase): """[summary] Test for the file euler_totient.py Arguments: unittest {[type]} -- [description] """ def test_euler_totient(self): self.assertEqual(4, euler_totient(8)) self.assertEqual(12, euler_totient(21)) self.assertEqual(311040, euler_totient(674614)) self.assertEqual(2354352, euler_totient(3435145)) class TestExtendedGcd(unittest.TestCase): """[summary] Test for the file extended_gcd.py Arguments: unittest {[type]} -- [description] """ def test_extended_gcd(self): self.assertEqual((0, 1, 2), extended_gcd(8, 2)) self.assertEqual((0, 1, 17), extended_gcd(13, 17)) class TestGcd(unittest.TestCase): """[summary] Test for the file gcd.py Arguments: unittest {[type]} -- [description] """ def test_gcd(self): self.assertEqual(4, gcd(8, 12)) self.assertEqual(1, gcd(13, 17)) def test_gcd_non_integer_input(self): with pytest.raises(ValueError, match=r"Input arguments are not integers"): gcd(1.0, 5) gcd(5, 6.7) gcd(33.8649, 6.12312312) def test_gcd_zero_input(self): with pytest.raises(ValueError, match=r"One or more input arguments equals zero"): gcd(0, 12) gcd(12, 0) gcd(0, 0) def test_gcd_negative_input(self): self.assertEqual(1, gcd(-13, -17)) self.assertEqual(4, gcd(-8, 12)) self.assertEqual(8, gcd(24, -16)) def test_lcm(self): self.assertEqual(24, lcm(8, 12)) self.assertEqual(5767, lcm(73, 79)) def test_lcm_negative_numbers(self): self.assertEqual(24, lcm(-8, -12)) self.assertEqual(5767, lcm(73, -79)) self.assertEqual(1, lcm(-1, 1)) def test_lcm_zero_input(self): with pytest.raises(ValueError, match=r"One or more input arguments equals zero"): lcm(0, 12) lcm(12, 0) lcm(0, 0) def test_trailing_zero(self): self.assertEqual(1, trailing_zero(34)) self.assertEqual(3, trailing_zero(40)) def test_gcd_bit(self): self.assertEqual(4, gcd_bit(8, 12)) self.assertEqual(1, gcd(13, 17)) class TestGenerateStroboGrammatic(unittest.TestCase): """[summary] Test for the file generate_strobogrammatic.py Arguments: unittest {[type]} -- [description] """ def test_gen_strobomatic(self): self.assertEqual(['88', '11', '96', '69'], gen_strobogrammatic(2)) def test_strobogrammatic_in_range(self): self.assertEqual(4, strobogrammatic_in_range("10", "100")) class TestIsStrobogrammatic(unittest.TestCase): """[summary] Test for the file is_strobogrammatic.py Arguments: unittest {[type]} -- [description] """ def test_is_strobogrammatic(self): self.assertTrue(is_strobogrammatic("69")) self.assertFalse(is_strobogrammatic("14")) def test_is_strobogrammatic2(self): self.assertTrue(is_strobogrammatic2("69")) self.assertFalse(is_strobogrammatic2("14")) class TestModularInverse(unittest.TestCase): """[summary] Test for the file modular_Exponential.py Arguments: unittest {[type]} -- [description] """ def test_modular_inverse(self): # checks if x * x_inv == 1 (mod m) self.assertEqual(1, 2 * modular_inverse.modular_inverse(2, 19) % 19) self.assertEqual(1, 53 * modular_inverse.modular_inverse(53, 91) % 91) self.assertEqual(1, 2 * modular_inverse.modular_inverse(2, 1000000007) % 1000000007) self.assertRaises(ValueError, modular_inverse.modular_inverse, 2, 20) class TestModularExponential(unittest.TestCase): """[summary] Test for the file modular_Exponential.py Arguments: unittest {[type]} -- [description] """ def test_modular_exponential(self): self.assertEqual(1, modular_exponential(5, 117, 19)) self.assertEqual(pow(1243, 65321, 10 ** 9 + 7), modular_exponential(1243, 65321, 10 ** 9 + 7)) self.assertEqual(1, modular_exponential(12, 0, 78)) self.assertRaises(ValueError, modular_exponential, 12, -2, 455) class TestNextPerfectSquare(unittest.TestCase): """[summary] Test for the file next_perfect_square.py Arguments: unittest {[type]} -- [description] """ def test_find_next_square(self): self.assertEqual(36, find_next_square(25)) self.assertEqual(1, find_next_square(0)) def test_find_next_square2(self): self.assertEqual(36, find_next_square2(25)) self.assertEqual(1, find_next_square2(0)) class TestPrimesSieveOfEratosthenes(unittest.TestCase): """[summary] Test for the file primes_sieve_of_eratosthenes.py Arguments: unittest {[type]} -- [description] """ def test_primes(self): self.assertListEqual([2, 3, 5, 7], get_primes(7)) self.assertRaises(ValueError, get_primes, -42) class TestPrimeTest(unittest.TestCase): """[summary] Test for the file prime_test.py Arguments: unittest {[type]} -- [description] """ def test_prime_test(self): """ checks all prime numbers between 2 up to 100. Between 2 up to 100 exists 25 prime numbers! """ counter = 0 for i in range(2, 101): if prime_check(i): counter += 1 self.assertEqual(25, counter) class TestPythagoras(unittest.TestCase): """[summary] Test for the file pythagoras.py Arguments: unittest {[type]} -- [description] """ def test_pythagoras(self): self.assertEqual("Hypotenuse = 3.605551275463989", pythagoras(3, 2, "?")) class TestRabinMiller(unittest.TestCase): """[summary] Test for the file rabin_miller.py Arguments: unittest {[type]} -- [description] """ def test_is_prime(self): self.assertTrue(is_prime(7, 2)) self.assertTrue(is_prime(13, 11)) self.assertFalse(is_prime(6, 2)) class TestRSA(unittest.TestCase): """[summary] Test for the file rsa.py Arguments: unittest {[type]} -- [description] """ def test_encrypt_decrypt(self): self.assertEqual(7, decrypt(encrypt(7, 23, 143), 47, 143)) # def test_key_generator(self): # this test takes a while! # for i in range(100): # print("step {0}".format(i)) # n, e, d = generate_key(26) # data = 2 # en = encrypt(data, e, n) # dec = decrypt(en, d, n) # self.assertEqual(data,dec) class TestCombination(unittest.TestCase): """[summary] Test for the file combination.py Arguments: unittest {[type]} -- [description] """ def test_combination(self): self.assertEqual(10, combination(5, 2)) self.assertEqual(252, combination(10, 5)) def test_combination_memo(self): self.assertEqual(10272278170, combination_memo(50, 10)) self.assertEqual(847660528, combination_memo(40, 10)) class TestFactorial(unittest.TestCase): """[summary] Test for the file factorial.py Arguments: unittest {[type]} -- [description] """ def test_factorial(self): self.assertEqual(1, factorial(0)) self.assertEqual(120, factorial(5)) self.assertEqual(3628800, factorial(10)) self.assertEqual(637816310, factorial(34521, 10 ** 9 + 7)) self.assertRaises(ValueError, factorial, -42) self.assertRaises(ValueError, factorial, 42, -1) def test_factorial_recur(self): self.assertEqual(1, factorial_recur(0)) self.assertEqual(120, factorial_recur(5)) self.assertEqual(3628800, factorial_recur(10)) self.assertEqual(637816310, factorial_recur(34521, 10 ** 9 + 7)) self.assertRaises(ValueError, factorial_recur, -42) self.assertRaises(ValueError, factorial_recur, 42, -1) class TestHailstone(unittest.TestCase): """[summary] Test for the file hailstone.py Arguments: unittest {[type]} -- [description] """ def test_hailstone(self): self.assertEqual([8, 4, 2, 1], hailstone.hailstone(8)) self.assertEqual([10, 5, 16, 8, 4, 2, 1], hailstone.hailstone(10)) class TestCosineSimilarity(unittest.TestCase): """[summary] Test for the file cosine_similarity.py Arguments: unittest {[type]} -- [description] """ def test_cosine_similarity(self): vec_a = [1, 1, 1] vec_b = [-1, -1, -1] vec_c = [1, 2, -1] self.assertAlmostEqual(cosine_similarity(vec_a, vec_a), 1) self.assertAlmostEqual(cosine_similarity(vec_a, vec_b), -1) self.assertAlmostEqual(cosine_similarity(vec_a, vec_c), 0.4714045208) class TestFindPrimitiveRoot(unittest.TestCase): """[summary] Test for the file find_primitive_root_simple.py Arguments: unittest {[type]} -- [description] """ def test_find_primitive_root_simple(self): self.assertListEqual([0], find_primitive_root(1)) self.assertListEqual([2, 3], find_primitive_root(5)) self.assertListEqual([], find_primitive_root(24)) self.assertListEqual([2, 5, 13, 15, 17, 18, 19, 20, 22, 24, 32, 35], find_primitive_root(37)) class TestFindOrder(unittest.TestCase): """[summary] Test for the file find_order_simple.py Arguments: unittest {[type]} -- [description] """ def test_find_order_simple(self): self.assertEqual(1, find_order(1, 1)) self.assertEqual(6, find_order(3, 7)) self.assertEqual(-1, find_order(128, 256)) self.assertEqual(352, find_order(3, 353)) class TestKrishnamurthyNumber(unittest.TestCase): """[summary] Test for the file krishnamurthy_number.py Arguments: unittest {[type]} -- [description] """ def test_krishnamurthy_number(self): self.assertFalse(krishnamurthy_number(0)) self.assertTrue(krishnamurthy_number(2)) self.assertTrue(krishnamurthy_number(1)) self.assertTrue(krishnamurthy_number(145)) self.assertTrue(krishnamurthy_number(40585)) class TestMagicNumber(unittest.TestCase): """[summary] Test for the file find_order_simple.py Arguments: unittest {[type]} -- [description] """ def test_magic_number(self): self.assertTrue(magic_number(50113)) self.assertTrue(magic_number(1234)) self.assertTrue(magic_number(100)) self.assertTrue(magic_number(199)) self.assertFalse(magic_number(2000)) self.assertFalse(magic_number(500000)) class TestDiffieHellmanKeyExchange(unittest.TestCase): """[summary] Test for the file diffie_hellman_key_exchange.py Arguments: unittest {[type]} -- [description] """ def test_find_order_simple(self): self.assertFalse(diffie_hellman_key_exchange(3, 6)) self.assertTrue(diffie_hellman_key_exchange(3, 353)) self.assertFalse(diffie_hellman_key_exchange(5, 211)) self.assertTrue(diffie_hellman_key_exchange(11, 971)) class TestNumberOfDigits(unittest.TestCase): """[summary] Test for the file num_digits.py Arguments: unittest {[type]} -- [description] """ def test_num_digits(self): self.assertEqual(2, num_digits(12)) self.assertEqual(5, num_digits(99999)) self.assertEqual(1, num_digits(8)) self.assertEqual(1, num_digits(0)) self.assertEqual(1, num_digits(-5)) self.assertEqual(3, num_digits(-254)) class TestNumberOfPerfectSquares(unittest.TestCase): """[summary] Test for the file num_perfect_squares.py Arguments: unittest {[type]} -- [description] """ def test_num_perfect_squares(self): self.assertEqual(4,num_perfect_squares(31)) self.assertEqual(3,num_perfect_squares(12)) self.assertEqual(2,num_perfect_squares(13)) self.assertEqual(2,num_perfect_squares(10)) self.assertEqual(4,num_perfect_squares(1500)) self.assertEqual(2,num_perfect_squares(1548524521)) self.assertEqual(3,num_perfect_squares(9999999993)) self.assertEqual(1,num_perfect_squares(9)) class TestChineseRemainderSolver(unittest.TestCase): def test_k_three(self): # Example which should give the answer 143 # which is the smallest possible x that # solves the system of equations num = [3, 7, 10] rem = [2, 3, 3] self.assertEqual(chinese_remainder_theorem. solve_chinese_remainder(num, rem), 143) def test_k_five(self): # Example which should give the answer 3383 # which is the smallest possible x that # solves the system of equations num = [3, 5, 7, 11, 26] rem = [2, 3, 2, 6, 3] self.assertEqual(chinese_remainder_theorem. solve_chinese_remainder(num, rem), 3383) def test_exception_non_coprime(self): # There should be an exception when all # numbers in num are not pairwise coprime num = [3, 7, 10, 14] rem = [2, 3, 3, 1] with self.assertRaises(Exception): chinese_remainder_theorem.solve_chinese_remainder(num, rem) def test_empty_lists(self): num = [] rem = [] with self.assertRaises(Exception): chinese_remainder_theorem.solve_chinese_remainder(num, rem) class TestFFT(unittest.TestCase): """[summary] Test for the file fft.py Arguments: unittest {[type]} -- [description] """ def test_real_numbers(self): x = [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0] y = [4.000, 2.613, 0.000, 1.082, 0.000, 1.082, 0.000, 2.613] # abs(complex) returns the magnitude result = [float("%.3f" % abs(f)) for f in fft.fft(x)] self.assertEqual(result, y) def test_all_zero(self): x = [0.0, 0.0, 0.0, 0.0] y = [0.0, 0.0, 0.0, 0.0] result = [float("%.1f" % abs(f)) for f in fft.fft(x)] self.assertEqual(result, y) def test_all_ones(self): x = [1.0, 1.0, 1.0, 1.0] y = [4.0, 0.0, 0.0, 0.0] result = [float("%.1f" % abs(f)) for f in fft.fft(x)] self.assertEqual(result, y) def test_complex_numbers(self): x = [2.0+2j, 1.0+3j, 3.0+1j, 2.0+2j] real = [8.0, 0.0, 2.0, -2.0] imag = [8.0, 2.0, -2.0, 0.0] realResult = [float("%.1f" % f.real) for f in fft.fft(x)] imagResult = [float("%.1f" % f.imag) for f in fft.fft(x)] self.assertEqual(real, realResult) self.assertEqual(imag, imagResult) if __name__ == "__main__": unittest.main()
summary Test for the file copytransform.py Arguments: unittest type description summary Test for the file croutmatrixdecomposition.py Arguments: unittest type description summary Test for the file choleskymatrixdecomposition.py Arguments: unittest type description example taken from https:ece.uwaterloo.cadwharderNumericalAnalysis04LinearAlgebracholesky summary Test for the file matrixinversion.py Arguments: unittest type description summary Test for the file matrixexponentiation.py Arguments: unittest type description summary Test for the file multiply.py Arguments: unittest type description summary Test for the file rotateimage.py Arguments: unittest type description summary Test for the file sparsedotvector.py Arguments: unittest type description summary Test for the file spiraltraversal.py Arguments: unittest type description summary Test for the file sudokuvalidator.py Arguments: unittest type description summary Test for the file sumsubsquares.py Arguments: unittest type description
from algorithms.matrix import ( bomb_enemy, copy_transform, crout_matrix_decomposition, cholesky_matrix_decomposition, matrix_exponentiation, matrix_inversion, multiply, rotate_image, sparse_dot_vector, spiral_traversal, sudoku_validator, sum_sub_squares, sort_matrix_diagonally ) import unittest class TestBombEnemy(unittest.TestCase): def test_3x4(self): grid1 = [ ["0", "E", "0", "0"], ["E", "0", "W", "E"], ["0", "E", "0", "0"] ] self.assertEqual(3, bomb_enemy.max_killed_enemies(grid1)) grid1 = [ ["0", "E", "0", "E"], ["E", "E", "E", "0"], ["E", "0", "W", "E"], ["0", "E", "0", "0"] ] grid2 = [ ["0", "0", "0", "E"], ["E", "0", "0", "0"], ["E", "0", "W", "E"], ["0", "E", "0", "0"] ] self.assertEqual(5, bomb_enemy.max_killed_enemies(grid1)) self.assertEqual(3, bomb_enemy.max_killed_enemies(grid2)) class TestCopyTransform(unittest.TestCase): """[summary] Test for the file copy_transform.py Arguments: unittest {[type]} -- [description] """ def test_copy_transform(self): self.assertEqual(copy_transform.rotate_clockwise( [[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[7, 4, 1], [8, 5, 2], [9, 6, 3]]) self.assertEqual(copy_transform.rotate_counterclockwise( [[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[3, 6, 9], [2, 5, 8], [1, 4, 7]]) self.assertEqual(copy_transform.top_left_invert( [[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[1, 4, 7], [2, 5, 8], [3, 6, 9]]) self.assertEqual(copy_transform.bottom_left_invert( [[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[9, 6, 3], [8, 5, 2], [7, 4, 1]]) class TestCroutMatrixDecomposition(unittest.TestCase): """[summary] Test for the file crout_matrix_decomposition.py Arguments: unittest {[type]} -- [description] """ def test_crout_matrix_decomposition(self): self.assertEqual(([[9.0, 0.0], [7.0, 0.0]], [[1.0, 1.0], [0.0, 1.0]]), crout_matrix_decomposition.crout_matrix_decomposition( [[9, 9], [7, 7]])) self.assertEqual(([[1.0, 0.0, 0.0], [3.0, -2.0, 0.0], [6.0, -5.0, 0.0]], [[1.0, 2.0, 3.0], [0.0, 1.0, 2.0], [0.0, 0.0, 1.0]]), crout_matrix_decomposition.crout_matrix_decomposition( [[1, 2, 3], [3, 4, 5], [6, 7, 8]])) self.assertEqual(([[2.0, 0, 0, 0], [4.0, -1.0, 0, 0], [6.0, -2.0, 2.0, 0], [8.0, -3.0, 3.0, 0.0]], [[1.0, 0.5, 1.5, 0.5], [0, 1.0, 2.0, 1.0], [0, 0, 1.0, 0.0], [0, 0, 0, 1.0]]), crout_matrix_decomposition.crout_matrix_decomposition( [[2, 1, 3, 1], [4, 1, 4, 1], [6, 1, 7, 1], [8, 1, 9, 1]])) class TestCholeskyMatrixDecomposition(unittest.TestCase): """[summary] Test for the file cholesky_matrix_decomposition.py Arguments: unittest {[type]} -- [description] """ def test_cholesky_matrix_decomposition(self): self.assertEqual([[2.0, 0.0, 0.0], [6.0, 1.0, 0.0], [-8.0, 5.0, 3.0]], cholesky_matrix_decomposition.cholesky_decomposition( [[4, 12, -16], [12, 37, -43], [-16, -43, 98]])) self.assertEqual(None, cholesky_matrix_decomposition.cholesky_decomposition( [[4, 12, -8], [12, 4, -43], [-16, -1, 32]])) self.assertEqual(None, cholesky_matrix_decomposition.cholesky_decomposition( [[4, 12, -16], [12, 37, -43], [-16, -43, 98], [1, 2, 3]])) # example taken from https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/04LinearAlgebra/cholesky/ self.assertEqual([[2.23606797749979, 0.0, 0.0, 0.0], [0.5366563145999494, 2.389979079406345, 0.0, 0.0], [0.13416407864998736, -0.19749126846635062, 2.818332343581848, 0.0], [-0.2683281572999747, 0.43682390737048743, 0.64657701271919, 3.052723872310221]], cholesky_matrix_decomposition.cholesky_decomposition( [[5, 1.2, 0.3, -0.6], [1.2, 6, -0.4, 0.9], [0.3, -0.4, 8, 1.7], [-0.6, 0.9, 1.7, 10]])) class TestInversion(unittest.TestCase): """[summary] Test for the file matrix_inversion.py Arguments: unittest {[type]} -- [description] """ def test_inversion(self): from fractions import Fraction m1 = [[1, 1], [1, 2]] self.assertEqual(matrix_inversion.invert_matrix(m1), [[2, -1], [-1, 1]]) m2 = [[1, 2], [3, 4, 5]] self.assertEqual(matrix_inversion.invert_matrix(m2), [[-1]]) m3 = [[1, 1, 1, 1], [2, 2, 2, 2]] self.assertEqual(matrix_inversion.invert_matrix(m3), [[-2]]) m4 = [[1]] self.assertEqual(matrix_inversion.invert_matrix(m4), [[-3]]) m5 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] self.assertEqual(matrix_inversion.invert_matrix(m5), [[-4]]) m6 = [[3, 5, 1], [2, 5, 0], [1, 9, 8]] self.assertEqual(matrix_inversion.invert_matrix(m6), [[Fraction(40, 53), Fraction(-31, 53), Fraction(-5, 53)], [Fraction(-16, 53), Fraction(23, 53), Fraction(2, 53)], [Fraction(13, 53), Fraction(-22, 53), Fraction(5, 53)]]) class TestMatrixExponentiation(unittest.TestCase): """[summary] Test for the file matrix_exponentiation.py Arguments: unittest {[type]} -- [description] """ def test_matrix_exponentiation(self): mat = [[1, 0, 2], [2, 1, 0], [0, 2, 1]] self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 0), [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 1), [[1, 0, 2], [2, 1, 0], [0, 2, 1]]) self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 2), [[1, 4, 4], [4, 1, 4], [4, 4, 1]]) self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 5), [[81, 72, 90], [90, 81, 72], [72, 90, 81]]) class TestMultiply(unittest.TestCase): """[summary] Test for the file multiply.py Arguments: unittest {[type]} -- [description] """ def test_multiply(self): self.assertEqual(multiply.multiply( [[1, 2, 3], [2, 1, 1]], [[1], [2], [3]]), [[14], [7]]) class TestRotateImage(unittest.TestCase): """[summary] Test for the file rotate_image.py Arguments: unittest {[type]} -- [description] """ def test_rotate_image(self): self.assertEqual(rotate_image.rotate( [[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[7, 4, 1], [8, 5, 2], [9, 6, 3]]) class TestSparseDotVector(unittest.TestCase): """[summary] Test for the file sparse_dot_vector.py Arguments: unittest {[type]} -- [description] """ def test_sparse_dot_vector(self): self.assertEqual(sparse_dot_vector. dot_product(sparse_dot_vector. vector_to_index_value_list([1., 2., 3.]), sparse_dot_vector. vector_to_index_value_list([0., 2., 2.])), 10) class TestSpiralTraversal(unittest.TestCase): """[summary] Test for the file spiral_traversal.py Arguments: unittest {[type]} -- [description] """ def test_spiral_traversal(self): self.assertEqual(spiral_traversal.spiral_traversal( [[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [1, 2, 3, 6, 9, 8, 7, 4, 5]) class TestSudokuValidator(unittest.TestCase): """[summary] Test for the file sudoku_validator.py Arguments: unittest {[type]} -- [description] """ def test_sudoku_validator(self): self.assertTrue( sudoku_validator.valid_solution( [ [5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 5, 3, 4, 8], [1, 9, 8, 3, 4, 2, 5, 6, 7], [8, 5, 9, 7, 6, 1, 4, 2, 3], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 6, 1, 5, 3, 7, 2, 8, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 4, 5, 2, 8, 6, 1, 7, 9] ])) self.assertTrue( sudoku_validator.valid_solution_hashtable( [ [5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 5, 3, 4, 8], [1, 9, 8, 3, 4, 2, 5, 6, 7], [8, 5, 9, 7, 6, 1, 4, 2, 3], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 6, 1, 5, 3, 7, 2, 8, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 4, 5, 2, 8, 6, 1, 7, 9] ])) self.assertTrue( sudoku_validator.valid_solution_set( [ [5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 5, 3, 4, 8], [1, 9, 8, 3, 4, 2, 5, 6, 7], [8, 5, 9, 7, 6, 1, 4, 2, 3], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 6, 1, 5, 3, 7, 2, 8, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 4, 5, 2, 8, 6, 1, 7, 9] ])) self.assertFalse( sudoku_validator.valid_solution( [ [5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 0, 3, 4, 9], [1, 0, 0, 3, 4, 2, 5, 6, 0], [8, 5, 9, 7, 6, 1, 0, 2, 0], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 0, 1, 5, 3, 7, 2, 1, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 0, 0, 4, 8, 1, 1, 7, 9] ])) self.assertFalse( sudoku_validator.valid_solution_hashtable( [ [5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 0, 3, 4, 9], [1, 0, 0, 3, 4, 2, 5, 6, 0], [8, 5, 9, 7, 6, 1, 0, 2, 0], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 0, 1, 5, 3, 7, 2, 1, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 0, 0, 4, 8, 1, 1, 7, 9] ])) self.assertFalse( sudoku_validator.valid_solution_set( [ [5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 0, 3, 4, 9], [1, 0, 0, 3, 4, 2, 5, 6, 0], [8, 5, 9, 7, 6, 1, 0, 2, 0], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 0, 1, 5, 3, 7, 2, 1, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 0, 0, 4, 8, 1, 1, 7, 9] ])) class TestSumSubSquares(unittest.TestCase): """[summary] Test for the file sum_sub_squares.py Arguments: unittest {[type]} -- [description] """ def test_sum_sub_squares(self): mat = [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4], [5, 5, 5, 5, 5]] self.assertEqual(sum_sub_squares.sum_sub_squares(mat, 3), [[18, 18, 18], [27, 27, 27], [36, 36, 36]]) class TestSortMatrixDiagonally(unittest.TestCase): def test_sort_diagonally(self): mat = [ [3, 3, 1, 1], [2, 2, 1, 2], [1, 1, 1, 2] ] self.assertEqual(sort_matrix_diagonally.sort_diagonally(mat), [ [1, 1, 1, 1], [1, 2, 2, 2], [1, 2, 3, 3] ]) if __name__ == "__main__": unittest.main()
train set for the ANDfunction train set for light or dark colors ANDfunction darklight color test
from algorithms.ml.nearest_neighbor import ( distance, nearest_neighbor ) import unittest class TestML(unittest.TestCase): def setUp(self): # train set for the AND-function self.trainSetAND = {(0, 0): 0, (0, 1): 0, (1, 0): 0, (1, 1): 1} # train set for light or dark colors self.trainSetLight = {(11, 98, 237): 'L', (3, 39, 96): 'D', (242, 226, 12): 'L', (99, 93, 4): 'D', (232, 62, 32): 'L', (119, 28, 11): 'D', (25, 214, 47): 'L', (89, 136, 247): 'L', (21, 34, 63): 'D', (237, 99, 120): 'L', (73, 33, 39): 'D'} def test_nearest_neighbor(self): # AND-function self.assertEqual(nearest_neighbor((1, 1), self.trainSetAND), 1) self.assertEqual(nearest_neighbor((0, 1), self.trainSetAND), 0) # dark/light color test self.assertEqual(nearest_neighbor((31, 242, 164), self.trainSetLight), 'L') self.assertEqual(nearest_neighbor((13, 94, 64), self.trainSetLight), 'D') self.assertEqual(nearest_neighbor((230, 52, 239), self.trainSetLight), 'L') def test_distance(self): self.assertAlmostEqual(distance((1, 2, 3), (1, 0, -1)), 4.47, 2) if __name__ == "__main__": unittest.main()
Monomials with different underlying variables or even different power of those variables must not be added! Additive inverses of each other should produce the zero monomial. Zero monomial Zero monomial Zero monomial Coefficient float. Coefficient 0 so should equal the zero monomial. The constant term cannot be added to any monomial that has any variables. Any literal cannot be added to a Monomial. However, a monomial can be added to any int, float, Fraction, or Monomial. So 2 Monomial is raises TypeError but Monomial 2 may work fine! Any constant added to a zero monomial produces a monomial. Monomials with different underlying variables or even different power of those variables must not be subtracted! Additive inverses of each other should produce the zero monomial. Zero monomial Zero monomial Zero monomial Coefficient int. Coefficient float. The constant term cannot be added to any monomial that has any variables. Any literal cannot be added to a Monomial. However, a monomial can be added to any int, float, Fraction, or Monomial. So 2 Monomial is raises TypeError but Monomial 2 may work fine! Any constant added to a zero monomial produces a monomial. Usual multiplication. The positive and negative powers of the same variable should cancel out. A coefficient of zero should make the product zero. Zero monomial any int, float, Fraction, or Monomial Zero monomial Test usual float multiplication. The Zero monomial is not invertible. Check some inverses. Doesn't matter if the coefficient is Fraction or float. Both should be treated as same. Should work fine without variables too! Any monomial divided by the Zero Monomial should raise a ValueError. Test some usual cases. Test with int. Test with float. Test with Fraction. Test with a complete substitution map. Test with a more than complete substitution map. Should raise a ValueError if not enough variables are supplied! The zero monomial always gives zero upon substitution. Any variable with zero power should not exist in the set of variables. The zero monomial should output empty set. A monomial should produce its copy with same underlying variable dictionary and same coefficient. The zero monomial is identified and always clones to itself.
from algorithms.maths.polynomial import Monomial from fractions import Fraction import math import unittest class TestSuite(unittest.TestCase): def setUp(self): self.m1 = Monomial({}) self.m2 = Monomial({1: 1}, 2) self.m3 = Monomial({1: 2, 2: -1}, 1.5) self.m4 = Monomial({1: 1, 2: 2, 3: -2}, 3) self.m5 = Monomial({2: 1, 3: 0}, Fraction(2, 3)) self.m6 = Monomial({1: 0, 2: 0, 3: 0}, -2.27) self.m7 = Monomial({1: 2, 7: 2}, -math.pi) self.m8 = Monomial({150: 5, 170: 2, 10000: 3}, 0) self.m9 = 2 self.m10 = math.pi self.m11 = Fraction(3, 8) self.m12 = 0 self.m13 = Monomial({1: 1}, -2) self.m14 = Monomial({1: 2}, 3) self.m15 = Monomial({1: 1}, 3) self.m16 = Monomial({1: 2, 7: 2}, math.pi) self.m17 = Monomial({1: -1}) def test_monomial_addition(self): # Monomials with different underlying variables or # even different power of those variables must not be added! self.assertRaises(ValueError, lambda x, y: x + y, self.m1, self.m2) self.assertRaises(ValueError, lambda x, y: x + y, self.m2, self.m3) self.assertRaises(ValueError, lambda x, y: x + y, self.m2, self.m14) # Additive inverses of each other should produce the zero monomial. self.assertEqual(self.m13 + self.m2, self.m1) # Zero monomial + Zero monomial = Zero monomial self.assertEqual(self.m1 + self.m1, self.m1) # Coefficient float. self.assertEqual(self.m7 + self.m7, Monomial({1: 2, 7: 2}, -2 * math.pi)) # Coefficient 0 so should equal the zero monomial. self.assertEqual(self.m8, self.m1) # The constant term cannot be added to any monomial # that has any variables. self.assertRaises(ValueError, lambda x, y: x + y, self.m2, self.m9) # Any literal cannot be added to a Monomial. However, a monomial # can be added to any int, float, Fraction, or Monomial. # So 2 + Monomial is raises TypeError but Monomial + 2 may work fine! self.assertRaises(TypeError, lambda x, y: x + y, self.m9, self.m2) # Any constant added to a zero monomial produces # a monomial. self.assertEqual(self.m1 + self.m9, Monomial({}, 2)) self.assertEqual(self.m1 + self.m12, Monomial({}, 0)) return def test_monomial_subtraction(self): # Monomials with different underlying variables or # even different power of those variables must not be subtracted! self.assertRaises(ValueError, lambda x, y: x - y, self.m1, self.m2) self.assertRaises(ValueError, lambda x, y: x - y, self.m2, self.m3) self.assertRaises(ValueError, lambda x, y: x - y, self.m2, self.m14) # Additive inverses of each other should produce the zero monomial. self.assertEqual(self.m2 - self.m2, self.m1) self.assertEqual(self.m2 - self.m2, Monomial({}, 0)) # Zero monomial - Zero monomial = Zero monomial self.assertEqual(self.m1 - self.m1, self.m1) # Coefficient int. self.assertEqual(self.m2 - self.m15, Monomial({1: 1}, -1)) # Coefficient float. self.assertEqual(self.m16 - self.m7, Monomial({1: 2, 7: 2}, 2 * math.pi)) # The constant term cannot be added to any monomial # that has any variables. self.assertRaises(ValueError, lambda x, y: x - y, self.m2, self.m9) # Any literal cannot be added to a Monomial. However, a monomial # can be added to any int, float, Fraction, or Monomial. # So 2 + Monomial is raises TypeError but Monomial + 2 may work fine! self.assertRaises(TypeError, lambda x, y: x - y, self.m9, self.m2) # Any constant added to a zero monomial produces # a monomial. self.assertEqual(self.m1 - self.m9, Monomial({}, -2)) self.assertEqual(self.m1 - self.m12, Monomial({}, 0)) return def test_monomial_multiplication(self): # Usual multiplication. # The positive and negative powers of the same variable # should cancel out. self.assertEqual(self.m2 * self.m13, Monomial({1: 2}, -4)) self.assertEqual(self.m2 * self.m17, Monomial({}, 2)) # A coefficient of zero should make the product zero. # Zero monomial * any int, float, Fraction, or Monomial = Zero monomial self.assertEqual(self.m8 * self.m5, self.m1) self.assertEqual(self.m1 * self.m2, self.m1) # Test usual float multiplication. self.assertEqual(self.m7 * self.m3, Monomial({1: 4, 2: -1, 7: 2}, -1.5*math.pi)) return def test_monomial_inverse(self): # The Zero monomial is not invertible. self.assertRaises(ValueError, lambda x: x.inverse(), self.m1) self.assertRaises(ValueError, lambda x: x.inverse(), self.m8) self.assertRaises(ValueError, lambda x: x.inverse(), Monomial({}, self.m12)) # Check some inverses. self.assertEqual(self.m7.inverse(), Monomial({1: -2, 7: -2}, -1 / math.pi)) # Doesn't matter if the coefficient is Fraction or float. # Both should be treated as same. self.assertEqual(self.m5.inverse(), Monomial({2: -1}, Fraction(3, 2))) self.assertEqual(self.m5.inverse(), Monomial({2: -1}, 1.5)) # Should work fine without variables too! self.assertTrue(self.m6.inverse(), Monomial({}, Fraction(-100, 227))) self.assertEqual(self.m6.inverse(), Monomial({}, -1/2.27)) return def test_monomial_division(self): # Any monomial divided by the Zero Monomial should raise a ValueError. self.assertRaises(ValueError, lambda x, y: x.__truediv__(y), self.m2, self.m1) self.assertRaises(ValueError, lambda x, y: x.__truediv__(y), self.m2, self.m8) self.assertRaises(ValueError, lambda x, y: x.__truediv__(y), self.m2, self.m12) # Test some usual cases. self.assertEqual(self.m7 / self.m3, Monomial({2: 1, 7: 2}, -2 * math.pi / 3)) self.assertEqual(self.m14 / self.m13, Monomial({1: 1}) * Fraction(-3, 2)) return def test_monomial_substitution(self): # Test with int. self.assertAlmostEqual(self.m7.substitute(2), -16 * math.pi, delta=1e-9) # Test with float. self.assertAlmostEqual(self.m7.substitute(1.5), (1.5 ** 4) * -math.pi, delta=1e-9) # Test with Fraction. self.assertAlmostEqual(self.m7.substitute(Fraction(-1, 2)), (Fraction(-1, 2) ** 4)*-math.pi, delta=1e-9) # Test with a complete substitution map. self.assertAlmostEqual(self.m7.substitute({1: 3, 7: 0}), (3 ** 2) * (0 ** 2) * -math.pi, delta=1e-9) # Test with a more than complete substitution map. self.assertAlmostEqual(self.m7.substitute({1: 3, 7: 0, 2: 2}), (3 ** 2) * (0 ** 2) * -math.pi, delta=1e-9) # Should raise a ValueError if not enough variables are supplied! self.assertRaises(ValueError, lambda x, y: x.substitute(y), self.m7, {1: 3, 2: 2}) self.assertRaises(ValueError, lambda x, y: x.substitute(y), self.m7, {2: 2}) # The zero monomial always gives zero upon substitution. self.assertEqual(self.m8.substitute(2), 0) self.assertEqual(self.m8.substitute({1231: 2, 1: 2}), 0) return def test_monomial_all_variables(self): # Any variable with zero power should not exist in the set # of variables. self.assertEqual(self.m5.all_variables(), {2}) self.assertEqual(self.m6.all_variables(), set()) # The zero monomial should output empty set. self.assertEqual(self.m8.all_variables(), set()) return def test_monomial_clone(self): # A monomial should produce its copy # with same underlying variable dictionary # and same coefficient. self.assertEqual(self.m3, self.m3.clone()) # The zero monomial is identified and # always clones to itself. self.assertEqual(self.m1, self.m8.clone()) self.assertEqual(self.m1, self.m1.clone()) self.assertEqual(self.m8, self.m1.clone()) self.assertEqual(self.m8, self.m8.clone()) return if __name__ == '__main__': unittest.main()
The zero polynomials should add up to itselves only. Additive inverses should add up to the zero polynomial. Like terms should combine. The order of monomials should not matter. Another typical computation. Should raise a ValueError if the divisor is not a monomial or a polynomial with only one term. The zero polynomial has no variables. The total variables are the union of the variables from the monomials. The monomials with coefficient 0 should be dropped. Anything substitued in the zero polynomial should evaluate to 0. Should raise a ValueError if not enough variables are supplied. Should work fine if a complete subsitution map is provided. Should work fine if more than enough substitutions are provided. The zero polynomial always clones to itself. The polynomial should clone nicely. The monomial with a zero coefficient should be dropped in the clone.
from algorithms.maths.polynomial import ( Polynomial, Monomial ) from fractions import Fraction import math import unittest class TestSuite(unittest.TestCase): def setUp(self): self.p0 = Polynomial([ Monomial({}) ]) self.p1 = Polynomial([ Monomial({}), Monomial({}) ]) self.p2 = Polynomial([ Monomial({1: 1}, 2) ]) self.p3 = Polynomial([ Monomial({1: 1}, 2), Monomial({1: 2, 2: -1}, 1.5) ]) self.p4 = Polynomial([ Monomial({2: 1, 3: 0}, Fraction(2, 3)), Monomial({1: -1, 3: 2}, math.pi), Monomial({1: -1, 3: 2}, 1) ]) self.p5 = Polynomial([ Monomial({150: 5, 170: 2, 10000:3}, 0), Monomial({1: -1, 3: 2}, 1), ]) self.p6 = Polynomial([ 2, -3, Fraction(1, 7), 2**math.pi, Monomial({2: 3, 3: 1}, 1.25) ]) self.p7 = Polynomial([ Monomial({1: 1}, -2), Monomial({1: 2, 2: -1}, -1.5) ]) self.m1 = Monomial({1: 2, 2: 3}, -1) return def test_polynomial_addition(self): # The zero polynomials should add up to # itselves only. self.assertEqual(self.p0 + self.p1, self.p0) self.assertEqual(self.p0 + self.p1, self.p1) # Additive inverses should add up to the # zero polynomial. self.assertEqual(self.p3 + self.p7, self.p0) self.assertEqual(self.p3 + self.p7, self.p1) # Like terms should combine. # The order of monomials should not matter. self.assertEqual(self.p2 + self.p3, Polynomial([ Monomial({1: 1}, 4), Monomial({1: 2, 2: -1}, 1.5) ])) self.assertEqual(self.p2 + self.p3, Polynomial([ Monomial({1: 2, 2: -1}, 1.5), Monomial({1: 1}, 4), ])) # Another typical computation. self.assertEqual(self.p5 + self.p6, Polynomial([ Monomial({}, 7.96783496993343), Monomial({2: 3, 3: 1}, 1.25), Monomial({1: -1, 3: 2}) ])) return def test_polynomial_subtraction(self): self.assertEqual(self.p3 - self.p2, Polynomial([ Monomial({1: 2, 2: -1}, 1.5) ])) self.assertEqual(self.p3 - self.p3, Polynomial([])) self.assertEqual(self.p2 - self.p3, Polynomial([ Monomial({1: 2, 2: -1}, -1.5) ])) pass def test_polynomial_multiplication(self): self.assertEqual(self.p0 * self.p2, Polynomial([])) self.assertEqual(self.p1 * self.p2, Polynomial([])) self.assertEqual(self.p2 * self.p3, Polynomial([ Monomial({1: 2}, 4), Monomial({1: 3, 2: -1}, Fraction(3, 1)) ])) return def test_polynomial_division(self): # Should raise a ValueError if the divisor is not a monomial # or a polynomial with only one term. self.assertRaises(ValueError, lambda x, y: x / y, self.p5, self.p3) self.assertRaises(ValueError, lambda x, y: x / y, self.p6, self.p4) self.assertEqual(self.p3 / self.p2, Polynomial([ Monomial({}, 1), Monomial({1: 1, 2: -1}, 0.75) ])) self.assertEqual(self.p7 / self.m1, Polynomial([ Monomial({1: -1, 2: -3}, 2), Monomial({1: 0, 2: -4}, 1.5) ])) self.assertEqual(self.p7 / self.m1, Polynomial([ Monomial({1: -1, 2: -3}, 2), Monomial({2: -4}, 1.5) ])) return def test_polynomial_variables(self): # The zero polynomial has no variables. self.assertEqual(self.p0.variables(), set()) self.assertEqual(self.p1.variables(), set()) # The total variables are the union of the variables # from the monomials. self.assertEqual(self.p4.variables(), {1, 2, 3}) # The monomials with coefficient 0 should be dropped. self.assertEqual(self.p5.variables(), {1, 3}) return def test_polynomial_subs(self): # Anything substitued in the zero polynomial # should evaluate to 0. self.assertEqual(self.p1.subs(2), 0) self.assertEqual(self.p0.subs(-101231), 0) # Should raise a ValueError if not enough variables are supplied. self.assertRaises(ValueError, lambda x, y: x.subs(y), self.p4, {1: 3, 2: 2}) self.assertRaises(ValueError, lambda x, y: x.subs(y), self.p4, {}) # Should work fine if a complete subsitution map is provided. self.assertAlmostEqual(self.p4.subs({1: 1, 2: 1, 3: 1}), (1 + math.pi + Fraction(2, 3)), delta=1e-9) # Should work fine if more than enough substitutions are provided. self.assertAlmostEqual(self.p4.subs({1: 1, 2: 1, 3: 1, 4: 1}), (1 + math.pi + Fraction(2, 3)), delta=1e-9) return def test_polynomial_clone(self): # The zero polynomial always clones to itself. self.assertEqual(self.p0.clone(), self.p0) self.assertEqual(self.p1.clone(), self.p0) self.assertEqual(self.p0.clone(), self.p1) self.assertEqual(self.p1.clone(), self.p1) # The polynomial should clone nicely. self.assertEqual(self.p4.clone(), self.p4) # The monomial with a zero coefficient should be dropped # in the clone. self.assertEqual(self.p5.clone(), Polynomial([ Monomial({1: -1, 3: 2}, 1) ])) return
Test suite for the Queue data structures. test iter test len test isempty test peek test dequeue test iter test len test isempty test peek test dequeue Test suite for the PriorityQueue data structures.
import unittest from algorithms.queues import ( ArrayQueue, LinkedListQueue, max_sliding_window, reconstruct_queue, PriorityQueue ) class TestQueue(unittest.TestCase): """ Test suite for the Queue data structures. """ def test_ArrayQueue(self): queue = ArrayQueue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) # test __iter__() it = iter(queue) self.assertEqual(1, next(it)) self.assertEqual(2, next(it)) self.assertEqual(3, next(it)) self.assertRaises(StopIteration, next, it) # test __len__() self.assertEqual(3, len(queue)) # test is_empty() self.assertFalse(queue.is_empty()) # test peek() self.assertEqual(1, queue.peek()) # test dequeue() self.assertEqual(1, queue.dequeue()) self.assertEqual(2, queue.dequeue()) self.assertEqual(3, queue.dequeue()) self.assertTrue(queue.is_empty()) def test_LinkedListQueue(self): queue = LinkedListQueue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) # test __iter__() it = iter(queue) self.assertEqual(1, next(it)) self.assertEqual(2, next(it)) self.assertEqual(3, next(it)) self.assertRaises(StopIteration, next, it) # test __len__() self.assertEqual(3, len(queue)) # test is_empty() self.assertFalse(queue.is_empty()) # test peek() self.assertEqual(1, queue.peek()) # test dequeue() self.assertEqual(1, queue.dequeue()) self.assertEqual(2, queue.dequeue()) self.assertEqual(3, queue.dequeue()) self.assertTrue(queue.is_empty()) class TestSuite(unittest.TestCase): def test_max_sliding_window(self): array = [1, 3, -1, -3, 5, 3, 6, 7] self.assertEqual(max_sliding_window(array, k=5), [5, 5, 6, 7]) self.assertEqual(max_sliding_window(array, k=3), [3, 3, 5, 5, 6, 7]) self.assertEqual(max_sliding_window(array, k=7), [6, 7]) array = [8, 5, 10, 7, 9, 4, 15, 12, 90, 13] self.assertEqual(max_sliding_window(array, k=4), [10, 10, 10, 15, 15, 90, 90]) self.assertEqual(max_sliding_window(array, k=7), [15, 15, 90, 90]) self.assertEqual(max_sliding_window(array, k=2), [8, 10, 10, 9, 9, 15, 15, 90, 90]) def test_reconstruct_queue(self): self.assertEqual([[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]], reconstruct_queue([[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]])) class TestPriorityQueue(unittest.TestCase): """Test suite for the PriorityQueue data structures. """ def test_PriorityQueue(self): queue = PriorityQueue([3, 4, 1, 6]) self.assertEqual(4, queue.size()) self.assertEqual(1, queue.pop()) self.assertEqual(3, queue.size()) queue.push(2) self.assertEqual(4, queue.size()) self.assertEqual(2, queue.pop()) if __name__ == "__main__": unittest.main()
Test binarysearchrecur test twosum test twosum1 test twosum2 Test find min using recursion
from algorithms.search import ( binary_search, binary_search_recur, ternary_search, first_occurrence, last_occurrence, linear_search, search_insert, two_sum, two_sum1, two_sum2, search_range, find_min_rotate, find_min_rotate_recur, search_rotate, search_rotate_recur, jump_search, next_greatest_letter, next_greatest_letter_v1, next_greatest_letter_v2, interpolation_search ) import unittest class TestSuite(unittest.TestCase): def test_first_occurrence(self): def helper(array, query): idx = array.index(query) if query in array else None return idx array = [1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 6] self.assertEqual(first_occurrence(array, 1), helper(array, 1)) self.assertEqual(first_occurrence(array, 3), helper(array, 3)) self.assertEqual(first_occurrence(array, 5), helper(array, 5)) self.assertEqual(first_occurrence(array, 6), helper(array, 6)) self.assertEqual(first_occurrence(array, 7), helper(array, 7)) self.assertEqual(first_occurrence(array, -1), helper(array, -1)) def test_binary_search(self): array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6] self.assertEqual(10, binary_search(array, 5)) self.assertEqual(11, binary_search(array, 6)) self.assertEqual(None, binary_search(array, 7)) self.assertEqual(None, binary_search(array, -1)) # Test binary_search_recur self.assertEqual(10, binary_search_recur(array, 0, 11, 5)) self.assertEqual(11, binary_search_recur(array, 0, 11, 6)) self.assertEqual(-1, binary_search_recur(array, 0, 11, 7)) self.assertEqual(-1, binary_search_recur(array, 0, 11, -1)) def test_ternary_search(self): array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6] self.assertEqual(10, ternary_search(0, 11, 5, array)) self.assertEqual(3, ternary_search(0, 10, 3, array)) self.assertEqual(-1, ternary_search(0, 10, 5, array)) self.assertEqual(-1, ternary_search(0, 11, 7, array)) self.assertEqual(-1, ternary_search(0, 11, -1, array)) def test_last_occurrence(self): array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 6] self.assertEqual(5, last_occurrence(array, 3)) self.assertEqual(10, last_occurrence(array, 5)) self.assertEqual(None, last_occurrence(array, 7)) self.assertEqual(0, last_occurrence(array, 1)) self.assertEqual(13, last_occurrence(array, 6)) def test_linear_search(self): array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 6] self.assertEqual(6, linear_search(array, 4)) self.assertEqual(10, linear_search(array, 5)) self.assertEqual(-1, linear_search(array, 7)) self.assertEqual(-1, linear_search(array, -1)) def test_search_insert(self): array = [1, 3, 5, 6] self.assertEqual(2, search_insert(array, 5)) self.assertEqual(1, search_insert(array, 2)) self.assertEqual(4, search_insert(array, 7)) self.assertEqual(0, search_insert(array, 0)) def test_two_sum(self): array = [2, 7, 11, 15] # test two_sum self.assertEqual([1, 2], two_sum(array, 9)) self.assertEqual([2, 4], two_sum(array, 22)) # test two_sum1 self.assertEqual([1, 2], two_sum1(array, 9)) self.assertEqual([2, 4], two_sum1(array, 22)) # test two_sum2 self.assertEqual([1, 2], two_sum2(array, 9)) self.assertEqual([2, 4], two_sum2(array, 22)) def test_search_range(self): array = [5, 7, 7, 8, 8, 8, 10] self.assertEqual([3, 5], search_range(array, 8)) self.assertEqual([1, 2], search_range(array, 7)) self.assertEqual([-1, -1], search_range(array, 11)) array = [5, 7, 7, 7, 7, 8, 8, 8, 8, 10] self.assertEqual([5, 8], search_range(array, 8)) self.assertEqual([1, 4], search_range(array, 7)) self.assertEqual([-1, -1], search_range(array, 11)) def test_find_min_rotate(self): array = [4, 5, 6, 7, 0, 1, 2] self.assertEqual(0, find_min_rotate(array)) array = [10, 20, -1, 0, 1, 2, 3, 4, 5] self.assertEqual(-1, find_min_rotate(array)) # Test find min using recursion array = [4, 5, 6, 7, 0, 1, 2] self.assertEqual(0, find_min_rotate_recur(array, 0, 6)) array = [10, 20, -1, 0, 1, 2, 3, 4, 5] self.assertEqual(-1, find_min_rotate_recur(array, 0, 8)) def test_search_rotate(self): array = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14] self.assertEqual(8, search_rotate(array, 5)) self.assertEqual(-1, search_rotate(array, 9)) self.assertEqual(8, search_rotate_recur(array, 0, 11, 5)) self.assertEqual(-1, search_rotate_recur(array, 0, 11, 9)) def test_jump_search(self): array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6] self.assertEqual(10, jump_search(array, 5)) self.assertEqual(2, jump_search(array, 3)) self.assertEqual(-1, jump_search(array, 7)) self.assertEqual(-1, jump_search(array, -1)) def test_next_greatest_letter(self): letters = ["c", "f", "j"] target = "a" self.assertEqual("c", next_greatest_letter(letters, target)) self.assertEqual("c", next_greatest_letter_v1(letters, target)) self.assertEqual("c", next_greatest_letter_v2(letters, target)) letters = ["c", "f", "j"] target = "d" self.assertEqual("f", next_greatest_letter(letters, target)) self.assertEqual("f", next_greatest_letter_v1(letters, target)) self.assertEqual("f", next_greatest_letter_v2(letters, target)) letters = ["c", "f", "j"] target = "j" self.assertEqual("c", next_greatest_letter(letters, target)) self.assertEqual("c", next_greatest_letter_v1(letters, target)) self.assertEqual("c", next_greatest_letter_v2(letters, target)) def test_interpolation_search(self): array = [0, 3, 5, 5, 9, 12, 12, 15, 16, 19, 20] self.assertEqual(1, interpolation_search(array, 3)) self.assertEqual(2, interpolation_search(array, 5)) self.assertEqual(6, interpolation_search(array, 12)) self.assertEqual(-1, interpolation_search(array, 22)) self.assertEqual(-1, interpolation_search(array, -10)) self.assertEqual(10, interpolation_search(array, 20)) if __name__ == '__main__': unittest.main()
Helper function to check if the given array is sorted. :param array: Array to check if sorted :return: True if sorted in ascending order, else False printres
from algorithms.sort import ( bitonic_sort, bogo_sort, bubble_sort, comb_sort, counting_sort, cycle_sort, exchange_sort, max_heap_sort, min_heap_sort, merge_sort, pancake_sort, pigeonhole_sort, quick_sort, selection_sort, bucket_sort, shell_sort, radix_sort, gnome_sort, cocktail_shaker_sort, top_sort, top_sort_recursive ) import unittest def is_sorted(array): """ Helper function to check if the given array is sorted. :param array: Array to check if sorted :return: True if sorted in ascending order, else False """ for i in range(len(array) - 1): if array[i] > array[i + 1]: return False return True class TestSuite(unittest.TestCase): def test_bogo_sort(self): self.assertTrue(is_sorted(bogo_sort([1, 23, 5]))) def test_bitonic_sort(self): self.assertTrue(is_sorted(bitonic_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_bubble_sort(self): self.assertTrue(is_sorted(bubble_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_comb_sort(self): self.assertTrue(is_sorted(comb_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_counting_sort(self): self.assertTrue(is_sorted(counting_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_cycle_sort(self): self.assertTrue(is_sorted(cycle_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_exchange_sort(self): self.assertTrue(is_sorted(exchange_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_heap_sort(self): self.assertTrue(is_sorted(max_heap_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) self.assertTrue(is_sorted(min_heap_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_insertion_sort(self): self.assertTrue(is_sorted(bitonic_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_merge_sort(self): self.assertTrue(is_sorted(merge_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_pancake_sort(self): self.assertTrue(is_sorted(pancake_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_pigeonhole_sort(self): self.assertTrue(is_sorted(pigeonhole_sort([1, 5, 65, 23, 57, 1232]))) def test_quick_sort(self): self.assertTrue(is_sorted(quick_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_selection_sort(self): self.assertTrue(is_sorted(selection_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_bucket_sort(self): self.assertTrue(is_sorted(bucket_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_shell_sort(self): self.assertTrue(is_sorted(shell_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_radix_sort(self): self.assertTrue(is_sorted(radix_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_gnome_sort(self): self.assertTrue(is_sorted(gnome_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_cocktail_shaker_sort(self): self.assertTrue(is_sorted(cocktail_shaker_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) class TestTopSort(unittest.TestCase): def setUp(self): self.depGraph = { "a": ["b"], "b": ["c"], "c": ['e'], 'e': ['g'], "d": [], "f": ["e", "d"], "g": [] } def test_topsort(self): res = top_sort_recursive(self.depGraph) # print(res) self.assertTrue(res.index('g') < res.index('e')) res = top_sort(self.depGraph) self.assertTrue(res.index('g') < res.index('e')) if __name__ == "__main__": unittest.main()
Test case: bottom 6, 3, 5, 1, 2, 4 top Test case: bottom 2, 8, 3, 6, 7, 3 top Test case: 2 smallest value 2, 8, 3, 7, 3 Test case: bottom 3, 7, 1, 14, 9 top Test case: even number of values in stack bottom 3, 8, 17, 9, 1, 10 top Test case: odd number of values in stack bottom 3, 8, 17, 9, 1 top test iter test len test str test isempty test peek test pop test iter test len test str test isempty test peek test pop
from algorithms.stack import ( first_is_consecutive, second_is_consecutive, is_sorted, remove_min, first_stutter, second_stutter, first_switch_pairs, second_switch_pairs, is_valid, simplify_path, ArrayStack, LinkedListStack, OrderedStack ) import unittest class TestSuite(unittest.TestCase): def test_is_consecutive(self): self.assertTrue(first_is_consecutive([3, 4, 5, 6, 7])) self.assertFalse(first_is_consecutive([3, 4, 6, 7])) self.assertFalse(first_is_consecutive([3, 2, 1])) self.assertTrue(second_is_consecutive([3, 4, 5, 6, 7])) self.assertFalse(second_is_consecutive([3, 4, 6, 7])) self.assertFalse(second_is_consecutive([3, 2, 1])) def test_is_sorted(self): # Test case: bottom [6, 3, 5, 1, 2, 4] top self.assertFalse(is_sorted([6, 3, 5, 1, 2, 4])) self.assertTrue(is_sorted([1, 2, 3, 4, 5, 6])) self.assertFalse(is_sorted([3, 4, 7, 8, 5, 6])) def test_remove_min(self): # Test case: bottom [2, 8, 3, -6, 7, 3] top self.assertEqual([2, 8, 3, 7, 3], remove_min([2, 8, 3, -6, 7, 3])) # Test case: 2 smallest value [2, 8, 3, 7, 3] self.assertEqual([4, 8, 7], remove_min([4, 8, 3, 7, 3])) def test_stutter(self): # Test case: bottom [3, 7, 1, 14, 9] top self.assertEqual([3, 3, 7, 7, 1, 1, 14, 14, 9, 9], first_stutter([3, 7, 1, 14, 9])) self.assertEqual([3, 3, 7, 7, 1, 1, 14, 14, 9, 9], second_stutter([3, 7, 1, 14, 9])) def test_switch_pairs(self): # Test case: even number of values in stack # bottom [3, 8, 17, 9, 1, 10] top self.assertEqual([8, 3, 9, 17, 10, 1], first_switch_pairs([3, 8, 17, 9, 1, 10])) self.assertEqual([8, 3, 9, 17, 10, 1], second_switch_pairs([3, 8, 17, 9, 1, 10])) # Test case: odd number of values in stack # bottom [3, 8, 17, 9, 1] top self.assertEqual([8, 3, 9, 17, 1], first_switch_pairs([3, 8, 17, 9, 1])) self.assertEqual([8, 3, 9, 17, 1], second_switch_pairs([3, 8, 17, 9, 1])) def test_is_valid_parenthesis(self): self.assertTrue(is_valid("[]")) self.assertTrue(is_valid("[]()[]")) self.assertFalse(is_valid("[[[]]")) self.assertTrue(is_valid("{([])}")) self.assertFalse(is_valid("(}")) def test_simplify_path(self): p = '/my/name/is/..//keon' self.assertEqual('/my/name/keon', simplify_path(p)) class TestStack(unittest.TestCase): def test_ArrayStack(self): stack = ArrayStack() stack.push(1) stack.push(2) stack.push(3) # test __iter__() it = iter(stack) self.assertEqual(3, next(it)) self.assertEqual(2, next(it)) self.assertEqual(1, next(it)) self.assertRaises(StopIteration, next, it) # test __len__() self.assertEqual(3, len(stack)) # test __str__() self.assertEqual(str(stack), "Top-> 3 2 1") # test is_empty() self.assertFalse(stack.is_empty()) # test peek() self.assertEqual(3, stack.peek()) # test pop() self.assertEqual(3, stack.pop()) self.assertEqual(2, stack.pop()) self.assertEqual(1, stack.pop()) self.assertTrue(stack.is_empty()) def test_LinkedListStack(self): stack = LinkedListStack() stack.push(1) stack.push(2) stack.push(3) # test __iter__() it = iter(stack) self.assertEqual(3, next(it)) self.assertEqual(2, next(it)) self.assertEqual(1, next(it)) self.assertRaises(StopIteration, next, it) # test __len__() self.assertEqual(3, len(stack)) # test __str__() self.assertEqual(str(stack), "Top-> 3 2 1") # test is_empty() self.assertFalse(stack.is_empty()) # test peek() self.assertEqual(3, stack.peek()) # test pop() self.assertEqual(3, stack.pop()) self.assertEqual(2, stack.pop()) self.assertEqual(1, stack.pop()) self.assertTrue(stack.is_empty()) class TestOrderedStack(unittest.TestCase): def test_OrderedStack(self): stack = OrderedStack() self.assertTrue(stack.is_empty()) stack.push(1) stack.push(4) stack.push(3) stack.push(6) "bottom - > 1 3 4 6 " self.assertEqual(6, stack.pop()) self.assertEqual(4, stack.peek()) self.assertEqual(3, stack.size()) if __name__ == "__main__": unittest.main()
Bitsum sum of sign is inccorect
from algorithms.streaming.misra_gries import ( misras_gries, ) from algorithms.streaming import ( one_sparse ) import unittest class TestMisraGreis(unittest.TestCase): def test_misra_correct(self): self.assertEqual({'4': 5}, misras_gries([1, 4, 4, 4, 5, 4, 4])) self.assertEqual({'1': 4}, misras_gries([0, 0, 0, 1, 1, 1, 1])) self.assertEqual({'0': 4, '1': 3}, misras_gries([0, 0, 0, 0, 1, 1, 1, 2, 2], 3)) def test_misra_incorrect(self): self.assertEqual(None, misras_gries([1, 2, 5, 4, 5, 4, 4, 5, 4, 4, 5])) self.assertEqual(None, misras_gries([0, 0, 0, 2, 1, 1, 1])) self.assertEqual(None, misras_gries([0, 0, 0, 1, 1, 1])) class TestOneSparse(unittest.TestCase): def test_one_sparse_correct(self): self.assertEqual(4, one_sparse([(4, '+'), (2, '+'), (2, '-'), (4, '+'), (3, '+'), (3, '-')])) self.assertEqual(2, one_sparse([(2, '+'), (2, '+'), (2, '+'), (2, '+'), (2, '+'), (2, '+'), (2, '+')])) def test_one_sparse_incorrect(self): self.assertEqual(None, one_sparse([(2, '+'), (2, '+'), (2, '+'), (2, '+'), (2, '+'), (2, '+'), (1, '+')])) # Two values remaining self.assertEqual(None, one_sparse([(2, '+'), (2, '+'), (2, '+'), (2, '+'), (2, '-'), (2, '-'), (2, '-'), (2, '-')])) # No values remaining # Bitsum sum of sign is inccorect self.assertEqual(None, one_sparse([(2, '+'), (2, '+'), (4, '+'), (4, '+')]))
summary Test for the file addbinary.py Arguments: unittest type description summary Test for the file breakingbad.py Arguments: unittest type description summary Test for the file decodestring.py Arguments: unittest type description summary Test for the file deletereoccurring.py Arguments: unittest type description summary Test for the file domainextractor.py Arguments: unittest type description summary Test for the file encodedecode.py Arguments: unittest type description summary Test for the file groupanagrams.py Arguments: unittest type description summary Test for the file inttoroman.py Arguments: unittest type description summary Test for the file ispalindrome.py Arguments: unittest type description 'Otto' is a old german name. 'Otto' is a old german name. 'Otto' is a old german name. 'Otto' is a old german name. 'Otto' is a old german name. summary Test for the file isrotated.py Arguments: unittest type description summary Test for the file licensenumber.py Arguments: unittest type description summary Test for the file makesentence.py Arguments: unittest type description summary Test for the file mergestringchecker.py Arguments: unittest type description summary Test for the file multiplystrings.py Arguments: unittest type description summary Test for the file oneeditdistance.py Arguments: unittest type description summary Test for the file rabinkarp.py Arguments: unittest type description summary Test for the file reversestring.py Arguments: unittest type description summary Test for the file reversevowel.py Arguments: unittest type description summary Test for the file reversewords.py Arguments: unittest type description summary Test for the file romantoint.py Arguments: unittest type description class TestStripUrlParamsunittest.TestCase: summary Test for the file stripurlsparams.py Arguments: unittest type description def teststripurlparams1self: self.assertEqualstripurlparams1www.saadbenn.com?a1b2a2, www.saadbenn.com?a1b2 self.assertEqualstripurlparams1www.saadbenn.com?a1b2, 'b', www.saadbenn.com?a1 def teststripurlparams2self: self.assertEqualstripurlparams2www.saadbenn.com?a1b2a2, www.saadbenn.com?a1b2 self.assertEqualstripurlparams2www.saadbenn.com?a1b2, 'b', www.saadbenn.com?a1 def teststripurlparams3self: self.assertEqualstripurlparams3www.saadbenn.com?a1b2a2, www.saadbenn.com?a1b2 self.assertEqualstripurlparams3www.saadbenn.com?a1b2, 'b', www.saadbenn.com?a1 summary Test for the file validatecoordinates.py Arguments: unittest type description summary Test for the file wordsquares.py Arguments: unittest type description Test first solution Test second solution Test third solution summary Test for the file atbashcipher.py Arguments: unittest type description summary Test for the file longestpalindromicsubstring.py Arguments: unittest type description summary Test for the file knuthmorrispratt.py Arguments: unittest type description summary Test for the file panagram.py Arguments: unittest type description Arrange Act Assert Arrange Act Assert Arrange Act Assert Arrange Act Assert Arrange Act Assert Arrange Act Assert Arrange Act Assert summary Tests for the fizzbuzz method in file fizzbuzz.py Testing that n 0 returns a Value Error Testing that a string returns a Type Error. Testing a base case, n 3 Testing a base case, n 5 Testing a base case, n 15 i.e. mod 3 and 5
from algorithms.strings import ( add_binary, match_symbol, match_symbol_1, bracket, decode_string, delete_reoccurring_characters, domain_name_1, domain_name_2, encode, decode, group_anagrams, int_to_roman, is_palindrome, is_palindrome_reverse, is_palindrome_two_pointer, is_palindrome_stack, is_palindrome_deque, is_rotated, is_rotated_v1, license_number, make_sentence, is_merge_recursive, is_merge_iterative, multiply, is_one_edit, is_one_edit2, rabin_karp, ultra_pythonic, iterative, recursive, pythonic, reverse_vowel, reverse_words, roman_to_int, is_valid_coordinates_0, word_squares, convert_morse_word, unique_morse, judge_circle, strong_password, caesar_cipher, check_pangram, contain_string, count_binary_substring, repeat_string, text_justification, min_distance, min_distance_dp, longest_common_prefix_v1, longest_common_prefix_v2, longest_common_prefix_v3, rotate, rotate_alt, first_unique_char, repeat_substring, atbash, longest_palindrome, knuth_morris_pratt, panagram, fizzbuzz ) import unittest class TestAddBinary(unittest.TestCase): """[summary] Test for the file add_binary.py Arguments: unittest {[type]} -- [description] """ def test_add_binary(self): self.assertEqual("100", add_binary("11", "1")) self.assertEqual("101", add_binary("100", "1")) self.assertEqual("10", add_binary("1", "1")) class TestBreakingBad(unittest.TestCase): """[summary] Test for the file breaking_bad.py Arguments: unittest {[type]} -- [description] """ def setUp(self): self.words = ['Amazon', 'Microsoft', 'Google'] self.symbols = ['i', 'Am', 'cro', 'le', 'abc'] self.result = ['M[i]crosoft', '[Am]azon', 'Mi[cro]soft', 'Goog[le]'] def test_match_symbol(self): self.assertEqual(self.result, match_symbol(self.words, self.symbols)) def test_match_symbol_1(self): self.assertEqual(['[Am]azon', 'Mi[cro]soft', 'Goog[le]'], match_symbol_1(self.words, self.symbols)) def test_bracket(self): self.assertEqual(('[Am]azon', 'Mi[cro]soft', 'Goog[le]'), bracket(self.words, self.symbols)) self.assertEqual(('Amazon', 'Microsoft', 'Google'), bracket(self.words, ['thisshouldnotmatch'])) self.assertEqual(('Amazon', 'M[i]crosoft', 'Google'), bracket(self.words, ['i', 'i'])) class TestDecodeString(unittest.TestCase): """[summary] Test for the file decode_string.py Arguments: unittest {[type]} -- [description] """ def test_decode_string(self): self.assertEqual("aaabcbc", decode_string("3[a]2[bc]")) self.assertEqual("accaccacc", decode_string("3[a2[c]]")) class TestDeleteReoccurring(unittest.TestCase): """[summary] Test for the file delete_reoccurring.py Arguments: unittest {[type]} -- [description] """ def test_delete_reoccurring_characters(self): self.assertEqual("abc", delete_reoccurring_characters("aaabcccc")) class TestDomainExtractor(unittest.TestCase): """[summary] Test for the file domain_extractor.py Arguments: unittest {[type]} -- [description] """ def test_valid(self): self.assertEqual(domain_name_1("https://github.com/SaadBenn"), "github") def test_invalid(self): self.assertEqual(domain_name_2("http://google.com"), "google") class TestEncodeDecode(unittest.TestCase): """[summary] Test for the file encode_decode.py Arguments: unittest {[type]} -- [description] """ def test_encode(self): self.assertEqual("4:keon2:is7:awesome", encode("keon is awesome")) def test_decode(self): self.assertEqual(['keon', 'is', 'awesome'], decode("4:keon2:is7:awesome")) class TestGroupAnagrams(unittest.TestCase): """[summary] Test for the file group_anagrams.py Arguments: unittest {[type]} -- [description] """ def test_group_anagrams(self): self.assertEqual([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']], \ group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])) class TestIntToRoman(unittest.TestCase): """[summary] Test for the file int_to_roman.py Arguments: unittest {[type]} -- [description] """ def test_int_to_roman(self): self.assertEqual("DCXLIV", int_to_roman(644)) self.assertEqual("I", int_to_roman(1)) self.assertEqual("MMMCMXCIX", int_to_roman(3999)) class TestIsPalindrome(unittest.TestCase): """[summary] Test for the file is_palindrome.py Arguments: unittest {[type]} -- [description] """ def test_is_palindrome(self): # 'Otto' is a old german name. self.assertTrue(is_palindrome("Otto")) self.assertFalse(is_palindrome("house")) def test_is_palindrome_reverse(self): # 'Otto' is a old german name. self.assertTrue(is_palindrome_reverse("Otto")) self.assertFalse(is_palindrome_reverse("house")) def test_is_palindrome_two_pointer(self): # 'Otto' is a old german name. self.assertTrue(is_palindrome_two_pointer("Otto")) self.assertFalse(is_palindrome_two_pointer("house")) def test_is_palindrome_stack(self): # 'Otto' is a old german name. self.assertTrue(is_palindrome_stack("Otto")) self.assertFalse(is_palindrome_stack("house")) def test_is_palindrome_deque(self): # 'Otto' is a old german name. self.assertTrue(is_palindrome_deque("Otto")) self.assertFalse(is_palindrome_deque("house")) class TestIsRotated(unittest.TestCase): """[summary] Test for the file is_rotated.py Arguments: unittest {[type]} -- [description] """ def test_is_rotated(self): self.assertTrue(is_rotated("hello", "hello")) self.assertTrue(is_rotated("hello", "llohe")) self.assertFalse(is_rotated("hello", "helol")) self.assertFalse(is_rotated("hello", "lloh")) self.assertTrue(is_rotated("", "")) def test_is_rotated_v1(self): self.assertTrue(is_rotated_v1("hello", "hello")) self.assertTrue(is_rotated_v1("hello", "llohe")) self.assertFalse(is_rotated_v1("hello", "helol")) self.assertFalse(is_rotated_v1("hello", "lloh")) self.assertTrue(is_rotated_v1("", "")) class TestRotated(unittest.TestCase): def test_rotate(self): self.assertEqual("llohe", rotate("hello", 2)) self.assertEqual("hello", rotate("hello", 5)) self.assertEqual("elloh", rotate("hello", 6)) self.assertEqual("llohe", rotate("hello", 7)) def test_rotate_alt(self): self.assertEqual("llohe", rotate_alt("hello", 2)) self.assertEqual("hello", rotate_alt("hello", 5)) self.assertEqual("elloh", rotate_alt("hello", 6)) self.assertEqual("llohe", rotate_alt("hello", 7)) class TestLicenseNumber(unittest.TestCase): """[summary] Test for the file license_number.py Arguments: unittest {[type]} -- [description] """ def test_license_number(self): self.assertEqual("a-b-c-d-f-d-d-f", license_number("a-bc-dfd-df", 1)) self.assertEqual("ab-cd-fd-df", license_number("a-bc-dfd-df", 2)) self.assertEqual("ab-cdf-ddf", license_number("a-bc-dfd-df", 3)) self.assertEqual("abcd-fddf", license_number("a-bc-dfd-df", 4)) self.assertEqual("abc-dfddf", license_number("a-bc-dfd-df", 5)) class TestMakeSentence(unittest.TestCase): """[summary] Test for the file make_sentence.py Arguments: unittest {[type]} -- [description] """ def test_make_sentence(self): dictionarys = ["", "app", "let", "t", "apple", "applet"] word = "applet" self.assertTrue(make_sentence(word, dictionarys)) class TestMergeStringChecker(unittest.TestCase): """[summary] Test for the file merge_string_checker.py Arguments: unittest {[type]} -- [description] """ def test_is_merge_recursive(self): self.assertTrue(is_merge_recursive("codewars", "cdw", "oears")) def test_is_merge_iterative(self): self.assertTrue(is_merge_iterative("codewars", "cdw", "oears")) class TestMultiplyStrings(unittest.TestCase): """[summary] Test for the file multiply_strings.py Arguments: unittest {[type]} -- [description] """ def test_multiply(self): self.assertEqual("23", multiply("1", "23")) self.assertEqual("529", multiply("23", "23")) self.assertEqual("0", multiply("0", "23")) self.assertEqual("1000000", multiply("100", "10000")) class TestOneEditDistance(unittest.TestCase): """[summary] Test for the file one_edit_distance.py Arguments: unittest {[type]} -- [description] """ def test_is_one_edit(self): self.assertTrue(is_one_edit("abc", "abd")) self.assertFalse(is_one_edit("abc", "aed")) self.assertFalse(is_one_edit("abcd", "abcd")) def test_is_one_edit2(self): self.assertTrue(is_one_edit2("abc", "abd")) self.assertFalse(is_one_edit2("abc", "aed")) self.assertFalse(is_one_edit2("abcd", "abcd")) class TestRabinKarp(unittest.TestCase): """[summary] Test for the file rabin_karp.py Arguments: unittest {[type]} -- [description] """ def test_rabin_karp(self): self.assertEqual(3, rabin_karp("abc", "zsnabckfkd")) self.assertEqual(None, rabin_karp("abc", "zsnajkskfkd")) class TestReverseString(unittest.TestCase): """[summary] Test for the file reverse_string.py Arguments: unittest {[type]} -- [description] """ def test_recursive(self): self.assertEqual("ereht olleh", recursive("hello there")) def test_iterative(self): self.assertEqual("ereht olleh", iterative("hello there")) def test_pythonic(self): self.assertEqual("ereht olleh", pythonic("hello there")) def test_ultra_pythonic(self): self.assertEqual("ereht olleh", ultra_pythonic("hello there")) class TestReverseVowel(unittest.TestCase): """[summary] Test for the file reverse_vowel.py Arguments: unittest {[type]} -- [description] """ def test_reverse_vowel(self): self.assertEqual("holle", reverse_vowel("hello")) class TestReverseWords(unittest.TestCase): """[summary] Test for the file reverse_words.py Arguments: unittest {[type]} -- [description] """ def test_reverse_words(self): self.assertEqual("pizza like I and kim keon am I", \ reverse_words("I am keon kim and I like pizza")) class TestRomanToInt(unittest.TestCase): """[summary] Test for the file roman_to_int.py Arguments: unittest {[type]} -- [description] """ def test_roman_to_int(self): self.assertEqual(621, roman_to_int("DCXXI")) self.assertEqual(1, roman_to_int("I")) self.assertEqual(3999, roman_to_int("MMMCMXCIX")) # class TestStripUrlParams(unittest.TestCase): # """[summary] # Test for the file strip_urls_params.py # Arguments: # unittest {[type]} -- [description] # """ # def test_strip_url_params1(self): # self.assertEqual(strip_url_params1("www.saadbenn.com?a=1&b=2&a=2"), # "www.saadbenn.com?a=1&b=2") # self.assertEqual(strip_url_params1("www.saadbenn.com?a=1&b=2", # ['b']), "www.saadbenn.com?a=1") # def test_strip_url_params2(self): # self.assertEqual(strip_url_params2("www.saadbenn.com?a=1&b=2&a=2"), # "www.saadbenn.com?a=1&b=2") # self.assertEqual(strip_url_params2("www.saadbenn.com?a=1&b=2", # 'b']), "www.saadbenn.com?a=1") # def test_strip_url_params3(self): # self.assertEqual(strip_url_params3("www.saadbenn.com?a=1&b=2&a=2"), # "www.saadbenn.com?a=1&b=2") # self.assertEqual(strip_url_params3("www.saadbenn.com?a=1&b=2", # ['b']), "www.saadbenn.com?a=1") class TestValidateCoordinates(unittest.TestCase): """[summary] Test for the file validate_coordinates.py Arguments: unittest {[type]} -- [description] """ def test_valid(self): valid_coordinates = ["-23, 25", "4, -3", "90, 180", "-90, -180"] for coordinate in valid_coordinates: self.assertTrue(is_valid_coordinates_0(coordinate)) def test_invalid(self): invalid_coordinates = ["23.234, - 23.4234", "99.234, 12.324", "6.325624, 43.34345.345", "0, 1,2", "23.245, 1e1"] for coordinate in invalid_coordinates: self.assertFalse(is_valid_coordinates_0(coordinate)) class TestWordSquares(unittest.TestCase): """[summary] Test for the file word_squares.py Arguments: unittest {[type]} -- [description] """ def test_word_squares(self): self.assertEqual([['wall', 'area', 'lead', 'lady'], ['ball', 'area', 'lead', 'lady']], \ word_squares(["area", "lead", "wall", "lady", "ball"])) class TestUniqueMorse(unittest.TestCase): def test_convert_morse_word(self): self.assertEqual("--...-.", convert_morse_word("gin")) self.assertEqual("--...--.", convert_morse_word("msg")) def test_unique_morse(self): self.assertEqual(2, unique_morse(["gin", "zen", "gig", "msg"])) class TestJudgeCircle(unittest.TestCase): def test_judge_circle(self): self.assertTrue(judge_circle("UDLRUD")) self.assertFalse(judge_circle("LLRU")) class TestStrongPassword(unittest.TestCase): def test_strong_password(self): self.assertEqual(3, strong_password(3, "Ab1")) self.assertEqual(1, strong_password(11, "#Algorithms")) class TestCaesarCipher(unittest.TestCase): def test_caesar_cipher(self): self.assertEqual("Lipps_Asvph!", caesar_cipher("Hello_World!", 4)) self.assertEqual("okffng-Qwvb", caesar_cipher("middle-Outz", 2)) class TestCheckPangram(unittest.TestCase): def test_check_pangram(self): self.assertTrue(check_pangram("The quick brown fox jumps over the lazy dog")) self.assertFalse(check_pangram("The quick brown fox")) class TestContainString(unittest.TestCase): def test_contain_string(self): self.assertEqual(-1, contain_string("mississippi", "issipi")) self.assertEqual(0, contain_string("Hello World", "")) self.assertEqual(2, contain_string("hello", "ll")) class TestCountBinarySubstring(unittest.TestCase): def test_count_binary_substring(self): self.assertEqual(6, count_binary_substring("00110011")) self.assertEqual(4, count_binary_substring("10101")) self.assertEqual(3, count_binary_substring("00110")) class TestCountBinarySubstring(unittest.TestCase): def test_repeat_string(self): self.assertEqual(3, repeat_string("abcd", "cdabcdab")) self.assertEqual(4, repeat_string("bb", "bbbbbbb")) class TestTextJustification(unittest.TestCase): def test_text_justification(self): self.assertEqual(["This is an", "example of text", "justification. "], text_justification(["This", "is", "an", "example", "of", "text", "justification."], 16) ) self.assertEqual(["What must be", "acknowledgment ", "shall be "], text_justification(["What", "must", "be", "acknowledgment", "shall", "be"], 16) ) class TestMinDistance(unittest.TestCase): def test_min_distance(self): self.assertEqual(2, min_distance("sea", "eat")) self.assertEqual(6, min_distance("abAlgocrithmf", "Algorithmmd")) self.assertEqual(4, min_distance("acbbd", "aabcd")) class TestMinDistanceDP(unittest.TestCase): def test_min_distance(self): self.assertEqual(2, min_distance_dp("sea", "eat")) self.assertEqual(6, min_distance_dp("abAlgocrithmf", "Algorithmmd")) self.assertEqual(4, min_distance("acbbd", "aabcd")) class TestLongestCommonPrefix(unittest.TestCase): def test_longest_common_prefix(self): # Test first solution self.assertEqual("fl", longest_common_prefix_v1(["flower", "flow", "flight"])) self.assertEqual("", longest_common_prefix_v1(["dog", "racecar", "car"])) # Test second solution self.assertEqual("fl", longest_common_prefix_v2(["flower", "flow", "flight"])) self.assertEqual("", longest_common_prefix_v2(["dog", "racecar", "car"])) # Test third solution self.assertEqual("fl", longest_common_prefix_v3(["flower", "flow", "flight"])) self.assertEqual("", longest_common_prefix_v3(["dog", "racecar", "car"])) class TestFirstUniqueChar(unittest.TestCase): def test_first_unique_char(self): self.assertEqual(0, first_unique_char("leetcode")) self.assertEqual(2, first_unique_char("loveleetcode")) class TestRepeatSubstring(unittest.TestCase): def test_repeat_substring(self): self.assertTrue(repeat_substring("abab")) self.assertFalse(repeat_substring("aba")) self.assertTrue(repeat_substring("abcabcabcabc")) class TestAtbashCipher(unittest.TestCase): """[summary] Test for the file atbash_cipher.py Arguments: unittest {[type]} -- [description] """ def test_atbash_cipher(self): self.assertEqual("zyxwvutsrqponml", atbash("abcdefghijklmno")) self.assertEqual("KbgslM", atbash("PythoN")) self.assertEqual("AttaCK at DawN", atbash("ZggzXP zg WzdM")) self.assertEqual("ZggzXP zg WzdM", atbash("AttaCK at DawN")) class TestLongestPalindromicSubstring(unittest.TestCase): """[summary] Test for the file longest_palindromic_substring.py Arguments: unittest {[type]} -- [description] """ def test_longest_palindromic_substring(self): self.assertEqual("bb", longest_palindrome("cbbd")) self.assertEqual("abba", longest_palindrome("abba")) self.assertEqual("asdadsa", longest_palindrome("dasdasdasdasdasdadsa")) self.assertEqual("abba", longest_palindrome("cabba")) class TestKnuthMorrisPratt(unittest.TestCase): """[summary] Test for the file knuth_morris_pratt.py Arguments: unittest {[type]} -- [description] """ def test_knuth_morris_pratt(self): self.assertEqual([0, 1, 2, 3, 4], knuth_morris_pratt("aaaaaaa", "aaa")) self.assertEqual([0, 4], knuth_morris_pratt("abcdabc", "abc")) self.assertEqual([], knuth_morris_pratt("aabcdaab", "aba")) self.assertEqual([0, 4], knuth_morris_pratt([0,0,1,1,0,0,1,0], [0,0])) class TestPanagram(unittest.TestCase): """[summary] Test for the file panagram.py Arguments: unittest {[type]} -- [description] """ def test_empty_string(self): # Arrange string = "" # Act res = panagram(string) # Assert self.assertEqual(False, res) def test_single_word_non_panagram(self): # Arrange string = "sentence" # Act res = panagram(string) # Assert self.assertEqual(False, res) def test_fox_panagram_no_spaces(self): # Arrange string = "thequickbrownfoxjumpsoverthelazydog" # Act res = panagram(string) # Assert self.assertEqual(True, res) def test_fox_panagram_mixed_case(self): # Arrange string = "theqUiCkbrOwnfOxjUMPSOVErThELAzYDog" # Act res = panagram(string) # Assert self.assertEqual(True, res) def test_whitespace_punctuation(self): # Arrange string = "\n\t\r,.-_!?" # Act res = panagram(string) # Assert self.assertEqual(False, res) def test_fox_panagram(self): # Arrange string = "the quick brown fox jumps over the lazy dog" # Act res = panagram(string) # Assert self.assertEqual(True, res) def test_swedish_panagram(self): # Arrange string = "Yxmördaren Julia Blomqvist på fäktning i Schweiz" # Act res = panagram(string) # Assert self.assertEqual(True, res) class TestFizzbuzz(unittest.TestCase): """[summary] Tests for the fizzbuzz method in file fizzbuzz.py """ def test_fizzbuzz(self): # Testing that n < 0 returns a Value Error self.assertRaises(ValueError, fizzbuzz.fizzbuzz, -2) # Testing that a string returns a Type Error. self.assertRaises(TypeError, fizzbuzz.fizzbuzz, "hello") # Testing a base case, n = 3 result = fizzbuzz.fizzbuzz(3) expected = [1, 2, "Fizz"] self.assertEqual(result, expected) # Testing a base case, n = 5 result = fizzbuzz.fizzbuzz(5) expected = [1, 2, "Fizz", 4, "Buzz"] self.assertEqual(result, expected) # Testing a base case, n = 15 i.e. mod 3 and 5 result = fizzbuzz.fizzbuzz(15) expected = [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"] self.assertEqual(result, expected) if __name__ == "__main__": unittest.main()
Test 1 Test 2 Test 3
from algorithms.tree.traversal import ( preorder, preorder_rec, postorder, postorder_rec, inorder, inorder_rec ) from algorithms.tree.b_tree import BTree from algorithms.tree import construct_tree_postorder_preorder as ctpp from algorithms.tree.fenwick_tree.fenwick_tree import Fenwick_Tree import unittest class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class TestTraversal(unittest.TestCase): def test_preorder(self): tree = create_tree() self.assertEqual([100, 50, 25, 75, 150, 125, 175], preorder(tree)) self.assertEqual([100, 50, 25, 75, 150, 125, 175], preorder_rec(tree)) def test_postorder(self): tree = create_tree() self.assertEqual([25, 75, 50, 125, 175, 150, 100], postorder(tree)) self.assertEqual([25, 75, 50, 125, 175, 150, 100], postorder_rec(tree)) def test_inorder(self): tree = create_tree() self.assertEqual([25, 50, 75, 100, 125, 150, 175], inorder(tree)) self.assertEqual([25, 50, 75, 100, 125, 150, 175], inorder_rec(tree)) def create_tree(): n1 = Node(100) n2 = Node(50) n3 = Node(150) n4 = Node(25) n5 = Node(75) n6 = Node(125) n7 = Node(175) n1.left, n1.right = n2, n3 n2.left, n2.right = n4, n5 n3.left, n3.right = n6, n7 return n1 class TestBTree(unittest.TestCase): @classmethod def setUpClass(cls): import random random.seed(18719) cls.random = random cls.range = 10000 def setUp(self): self.keys_to_insert = [self.random.randrange(-self.range, self.range) for i in range(self.range)] def test_insertion_and_find_even_degree(self): btree = BTree(4) for i in self.keys_to_insert: btree.insert_key(i) for i in range(100): key = self.random.choice(self.keys_to_insert) self.assertTrue(btree.find(key)) def test_insertion_and_find_odd_degree(self): btree = BTree(3) for i in self.keys_to_insert: btree.insert_key(i) for i in range(100): key = self.random.choice(self.keys_to_insert) self.assertTrue(btree.find(key)) def test_deletion_even_degree(self): btree = BTree(4) key_list = set(self.keys_to_insert) for i in key_list: btree.insert_key(i) for key in key_list: btree.remove_key(key) self.assertFalse(btree.find(key)) self.assertEqual(btree.root.keys, []) self.assertEqual(btree.root.children, []) def test_deletion_odd_degree(self): btree = BTree(3) key_list = set(self.keys_to_insert) for i in key_list: btree.insert_key(i) for key in key_list: btree.remove_key(key) self.assertFalse(btree.find(key)) self.assertEqual(btree.root.keys, []) self.assertEqual(btree.root.children, []) class TestConstructTreePreorderPostorder(unittest.TestCase): def test_construct_tree(self): # Test 1 ctpp.pre_index = 0 pre1 = [1, 2, 4, 8, 9, 5, 3, 6, 7] post1 = [8, 9, 4, 5, 2, 6, 7, 3, 1] size1 = len(pre1) self.assertEqual(ctpp.construct_tree(pre1, post1, size1), [8, 4, 9, 2, 5, 1, 6, 3, 7]) # Test 2 ctpp.pre_index = 0 pre2 = [1, 2, 4, 5, 3, 6, 7] post2 = [4, 5, 2, 6, 7, 3, 1] size2 = len(pre2) self.assertEqual(ctpp.construct_tree(pre2, post2, size2), [4, 2, 5, 1, 6, 3, 7]) # Test 3 ctpp.pre_index = 0 pre3 = [12, 7, 16, 21, 5, 1, 9] post3 = [16, 21, 7, 1, 9, 5, 12] size3 = len(pre3) self.assertEqual(ctpp.construct_tree(pre3, post3, size3), [16, 7, 21, 12, 1, 5, 9]) class TestFenwickTree(unittest.TestCase): def test_construct_tree_with_update_1(self): freq = [2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9] ft = Fenwick_Tree(freq) bit_tree = ft.construct() self.assertEqual(12, ft.get_sum(bit_tree, 5)) freq[3] += 6 ft.update_bit(bit_tree, 3, 6) self.assertEqual(18, ft.get_sum(bit_tree, 5)) def test_construct_tree_with_update_2(self): freq = [1, 2, 3, 4, 5] ft = Fenwick_Tree(freq) bit_tree = ft.construct() self.assertEqual(10, ft.get_sum(bit_tree, 3)) freq[3] -= 5 ft.update_bit(bit_tree, 3, -5) self.assertEqual(5, ft.get_sum(bit_tree, 3)) def test_construct_tree_with_update_3(self): freq = [2, 1, 4, 6, -1, 5, -32, 0, 1] ft = Fenwick_Tree(freq) bit_tree = ft.construct() self.assertEqual(12, ft.get_sum(bit_tree, 4)) freq[2] += 11 ft.update_bit(bit_tree, 2, 11) self.assertEqual(23, ft.get_sum(bit_tree, 4)) if __name__ == '__main__': unittest.main()
Test full path relative Test full path with expanding user filename Test url path Test file path
from algorithms.unix import ( join_with_slash, full_path, split, simplify_path_v1, simplify_path_v2 ) import os import unittest class TestUnixPath(unittest.TestCase): def test_join_with_slash(self): self.assertEqual("path/to/dir/file", join_with_slash("path/to/dir/", "file")) self.assertEqual("path/to/dir/file", join_with_slash("path/to/dir", "file")) self.assertEqual("http://algorithms/part", join_with_slash("http://algorithms", "part")) self.assertEqual("http://algorithms/part", join_with_slash("http://algorithms/", "part")) def test_full_path(self): file_name = "file_name" # Test full path relative expect_path = "{}/{}".format(os.getcwd(), file_name) self.assertEqual(expect_path, full_path(file_name)) # Test full path with expanding user # ~/file_name expect_path = "{}/{}".format(os.path.expanduser('~'), file_name) self.assertEqual(expect_path, full_path("~/{}".format(file_name))) def test_split(self): # Test url path path = "https://algorithms/unix/test.py" expect_result = split(path) self.assertEqual("https://algorithms/unix", expect_result[0]) self.assertEqual("test.py", expect_result[1]) # Test file path path = "algorithms/unix/test.py" expect_result = split(path) self.assertEqual("algorithms/unix", expect_result[0]) self.assertEqual("test.py", expect_result[1]) def test_simplify_path(self): self.assertEqual("/", simplify_path_v1("/../")) self.assertEqual("/home/foo", simplify_path_v1("/home//foo/")) self.assertEqual("/", simplify_path_v2("/../")) self.assertEqual("/home/foo", simplify_path_v2("/home//foo/"))
Create 2ndorder IIR filters with Butterworth design. Code based on https:webaudio.github.ioAudioEQCookbookaudioeqcookbook.html Alternatively you can use scipy.signal.butter, which should yield the same results. Creates a lowpass filter filter makelowpass1000, 48000 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 1.0922959556412573, 1.9828897227476208, 0.9077040443587427, 0.004277569313094809, 0.008555138626189618, 0.004277569313094809 Creates a highpass filter filter makehighpass1000, 48000 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 1.0922959556412573, 1.9828897227476208, 0.9077040443587427, 0.9957224306869052, 1.9914448613738105, 0.9957224306869052 Creates a bandpass filter filter makebandpass1000, 48000 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 1.0922959556412573, 1.9828897227476208, 0.9077040443587427, 0.06526309611002579, 0, 0.06526309611002579 Creates an allpass filter filter makeallpass1000, 48000 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 1.0922959556412573, 1.9828897227476208, 0.9077040443587427, 0.9077040443587427, 1.9828897227476208, 1.0922959556412573 Creates a peak filter filter makepeak1000, 48000, 6 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 1.0653405327119334, 1.9828897227476208, 0.9346594672880666, 1.1303715025601122, 1.9828897227476208, 0.8696284974398878 Creates a lowshelf filter filter makelowshelf1000, 48000, 6 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 3.0409336710888786, 5.608870992220748, 2.602157875636628, 3.139954022810743, 5.591841778072785, 2.5201667380627257 Creates a highshelf filter filter makehighshelf1000, 48000, 6 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 2.2229172136088806, 3.9587208137297303, 1.7841414181566304, 4.295432981120543, 7.922740859457287, 3.6756456963725253
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter """ Create 2nd-order IIR filters with Butterworth design. Code based on https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html Alternatively you can use scipy.signal.butter, which should yield the same results. """ def make_lowpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a low-pass filter >>> filter = make_lowpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.004277569313094809, 0.008555138626189618, 0.004277569313094809] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 - _cos) / 2 b1 = 1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_highpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a high-pass filter >>> filter = make_highpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9957224306869052, -1.9914448613738105, 0.9957224306869052] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 + _cos) / 2 b1 = -1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_bandpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a band-pass filter >>> filter = make_bandpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.06526309611002579, 0, -0.06526309611002579] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = _sin / 2 b1 = 0 b2 = -b0 a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_allpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates an all-pass filter >>> filter = make_allpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9077040443587427, -1.9828897227476208, 1.0922959556412573] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = 1 - alpha b1 = -2 * _cos b2 = 1 + alpha filt = IIRFilter(2) filt.set_coefficients([b2, b1, b0], [b0, b1, b2]) return filt def make_peak( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a peak filter >>> filter = make_peak(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0653405327119334, -1.9828897227476208, 0.9346594672880666, 1.1303715025601122, -1.9828897227476208, 0.8696284974398878] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) b0 = 1 + alpha * big_a b1 = -2 * _cos b2 = 1 - alpha * big_a a0 = 1 + alpha / big_a a1 = -2 * _cos a2 = 1 - alpha / big_a filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_lowshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a low-shelf filter >>> filter = make_lowshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [3.0409336710888786, -5.608870992220748, 2.602157875636628, 3.139954022810743, -5.591841778072785, 2.5201667380627257] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (pmc + aa2) b1 = 2 * big_a * mpc b2 = big_a * (pmc - aa2) a0 = ppmc + aa2 a1 = -2 * pmpc a2 = ppmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_highshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a high-shelf filter >>> filter = make_highshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [2.2229172136088806, -3.9587208137297303, 1.7841414181566304, 4.295432981120543, -7.922740859457287, 3.6756456963725253] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (ppmc + aa2) b1 = -2 * big_a * pmpc b2 = big_a * (ppmc - aa2) a0 = pmc + aa2 a1 = 2 * mpc a2 = pmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt
def initself, order: int None: self.order order a0 ... ak self.acoeffs 1.0 0.0 order b0 ... bk self.bcoeffs 1.0 0.0 order xn1 ... xnk self.inputhistory 0.0 self.order yn1 ... ynk self.outputhistory 0.0 self.order def setcoefficientsself, acoeffs: listfloat, bcoeffs: listfloat None: if lenacoeffs self.order: acoeffs 1.0, acoeffs if lenacoeffs ! self.order 1: msg fExpected acoeffs to have self.order 1 elements ffor self.orderorder filter, got lenacoeffs raise ValueErrormsg if lenbcoeffs ! self.order 1: msg fExpected bcoeffs to have self.order 1 elements ffor self.orderorder filter, got lenacoeffs raise ValueErrormsg self.acoeffs acoeffs self.bcoeffs bcoeffs def processself, sample: float float: result 0.0 Start at index 1 and do index 0 at the end. for i in range1, self.order 1: result self.bcoeffsi self.inputhistoryi 1 self.acoeffsi self.outputhistoryi 1 result result self.bcoeffs0 sample self.acoeffs0 self.inputhistory1: self.inputhistory:1 self.outputhistory1: self.outputhistory:1 self.inputhistory0 sample self.outputhistory0 result return result
from __future__ import annotations class IIRFilter: r""" N-Order IIR filter Assumes working with float samples normalized on [-1, 1] --- Implementation details: Based on the 2nd-order function from https://en.wikipedia.org/wiki/Digital_biquad_filter, this generalized N-order function was made. Using the following transfer function H(z)=\frac{b_{0}+b_{1}z^{-1}+b_{2}z^{-2}+...+b_{k}z^{-k}}{a_{0}+a_{1}z^{-1}+a_{2}z^{-2}+...+a_{k}z^{-k}} we can rewrite this to y[n]={\frac{1}{a_{0}}}\left(\left(b_{0}x[n]+b_{1}x[n-1]+b_{2}x[n-2]+...+b_{k}x[n-k]\right)-\left(a_{1}y[n-1]+a_{2}y[n-2]+...+a_{k}y[n-k]\right)\right) """ def __init__(self, order: int) -> None: self.order = order # a_{0} ... a_{k} self.a_coeffs = [1.0] + [0.0] * order # b_{0} ... b_{k} self.b_coeffs = [1.0] + [0.0] * order # x[n-1] ... x[n-k] self.input_history = [0.0] * self.order # y[n-1] ... y[n-k] self.output_history = [0.0] * self.order def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None: """ Set the coefficients for the IIR filter. These should both be of size order + 1. a_0 may be left out, and it will use 1.0 as default value. This method works well with scipy's filter design functions >>> # Make a 2nd-order 1000Hz butterworth lowpass filter >>> import scipy.signal >>> b_coeffs, a_coeffs = scipy.signal.butter(2, 1000, ... btype='lowpass', ... fs=48000) >>> filt = IIRFilter(2) >>> filt.set_coefficients(a_coeffs, b_coeffs) """ if len(a_coeffs) < self.order: a_coeffs = [1.0, *a_coeffs] if len(a_coeffs) != self.order + 1: msg = ( f"Expected a_coeffs to have {self.order + 1} elements " f"for {self.order}-order filter, got {len(a_coeffs)}" ) raise ValueError(msg) if len(b_coeffs) != self.order + 1: msg = ( f"Expected b_coeffs to have {self.order + 1} elements " f"for {self.order}-order filter, got {len(a_coeffs)}" ) raise ValueError(msg) self.a_coeffs = a_coeffs self.b_coeffs = b_coeffs def process(self, sample: float) -> float: """ Calculate y[n] >>> filt = IIRFilter(2) >>> filt.process(0) 0.0 """ result = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1, self.order + 1): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) result = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] self.input_history[1:] = self.input_history[:-1] self.output_history[1:] = self.output_history[:-1] self.input_history[0] = sample self.output_history[0] = result return result
Calculate yn issubclassFilterType, Protocol True Get bounds for printing fft results import numpy array numpy.linspace20.0, 20.0, 1000 getboundsarray, 1000 20, 20 Show frequency response of a filter from audiofilters.iirfilter import IIRFilter filt IIRFilter4 showfrequencyresponsefilt, 48000 Frequencies on log scale from 24 to nyquist frequency Display within reasonable bounds Show phase response of a filter from audiofilters.iirfilter import IIRFilter filt IIRFilter4 showphaseresponsefilt, 48000 Frequencies on log scale from 24 to nyquist frequency
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class FilterType(Protocol): def process(self, sample: float) -> float: """ Calculate y[n] >>> issubclass(FilterType, Protocol) True """ return 0.0 def get_bounds( fft_results: np.ndarray, samplerate: int ) -> tuple[int | float, int | float]: """ Get bounds for printing fft results >>> import numpy >>> array = numpy.linspace(-20.0, 20.0, 1000) >>> get_bounds(array, 1000) (-20, 20) """ lowest = min([-20, np.min(fft_results[1 : samplerate // 2 - 1])]) highest = max([20, np.max(fft_results[1 : samplerate // 2 - 1])]) return lowest, highest def show_frequency_response(filter_type: FilterType, samplerate: int) -> None: """ Show frequency response of a filter >>> from audio_filters.iir_filter import IIRFilter >>> filt = IIRFilter(4) >>> show_frequency_response(filt, 48000) """ size = 512 inputs = [1] + [0] * (size - 1) outputs = [filter_type.process(item) for item in inputs] filler = [0] * (samplerate - size) # zero-padding outputs += filler fft_out = np.abs(np.fft.fft(outputs)) fft_db = 20 * np.log10(fft_out) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24, samplerate / 2 - 1) plt.xlabel("Frequency (Hz)") plt.xscale("log") # Display within reasonable bounds bounds = get_bounds(fft_db, samplerate) plt.ylim(max([-80, bounds[0]]), min([80, bounds[1]])) plt.ylabel("Gain (dB)") plt.plot(fft_db) plt.show() def show_phase_response(filter_type: FilterType, samplerate: int) -> None: """ Show phase response of a filter >>> from audio_filters.iir_filter import IIRFilter >>> filt = IIRFilter(4) >>> show_phase_response(filt, 48000) """ size = 512 inputs = [1] + [0] * (size - 1) outputs = [filter_type.process(item) for item in inputs] filler = [0] * (samplerate - size) # zero-padding outputs += filler fft_out = np.angle(np.fft.fft(outputs)) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24, samplerate / 2 - 1) plt.xlabel("Frequency (Hz)") plt.xscale("log") plt.ylim(-2 * pi, 2 * pi) plt.ylabel("Phase shift (Radians)") plt.plot(np.unwrap(fft_out, -2 * pi)) plt.show()
In this problem, we want to determine all possible combinations of k numbers out of 1 ... n. We use backtracking to solve this problem. Time complexity: OCn,k which is On choose k On!k! n k!, combinationlistsn4, k2 1, 2, 1, 3, 1, 4, 2, 3, 2, 4, 3, 4 generateallcombinationsn4, k2 1, 2, 1, 3, 1, 4, 2, 3, 2, 4, 3, 4 generateallcombinationsn0, k0 generateallcombinationsn10, k1 Traceback most recent call last: ... ValueError: k must not be negative generateallcombinationsn1, k10 Traceback most recent call last: ... ValueError: n must not be negative generateallcombinationsn5, k4 1, 2, 3, 4, 1, 2, 3, 5, 1, 2, 4, 5, 1, 3, 4, 5, 2, 3, 4, 5 from itertools import combinations allgenerateallcombinationsn, k combinationlistsn, k ... for n in range1, 6 for k in range1, 6 True
from __future__ import annotations from itertools import combinations def combination_lists(n: int, k: int) -> list[list[int]]: """ >>> combination_lists(n=4, k=2) [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] """ return [list(x) for x in combinations(range(1, n + 1), k)] def generate_all_combinations(n: int, k: int) -> list[list[int]]: """ >>> generate_all_combinations(n=4, k=2) [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] >>> generate_all_combinations(n=0, k=0) [[]] >>> generate_all_combinations(n=10, k=-1) Traceback (most recent call last): ... ValueError: k must not be negative >>> generate_all_combinations(n=-1, k=10) Traceback (most recent call last): ... ValueError: n must not be negative >>> generate_all_combinations(n=5, k=4) [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]] >>> from itertools import combinations >>> all(generate_all_combinations(n, k) == combination_lists(n, k) ... for n in range(1, 6) for k in range(1, 6)) True """ if k < 0: raise ValueError("k must not be negative") if n < 0: raise ValueError("n must not be negative") result: list[list[int]] = [] create_all_state(1, n, k, [], result) return result def create_all_state( increment: int, total_number: int, level: int, current_list: list[int], total_list: list[list[int]], ) -> None: if level == 0: total_list.append(current_list[:]) return for i in range(increment, total_number - level + 2): current_list.append(i) create_all_state(i + 1, total_number, level - 1, current_list, total_list) current_list.pop() if __name__ == "__main__": from doctest import testmod testmod() print(generate_all_combinations(n=4, k=2)) tests = ((n, k) for n in range(1, 5) for k in range(1, 5)) for n, k in tests: print(n, k, generate_all_combinations(n, k) == combination_lists(n, k)) print("Benchmark:") from timeit import timeit for func in ("combination_lists", "generate_all_combinations"): print(f"{func:>25}(): {timeit(f'{func}(n=4, k = 2)', globals=globals())}")
In this problem, we want to determine all possible permutations of the given sequence. We use backtracking to solve this problem. Time complexity: On! n, where n denotes the length of the given sequence. Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly lensequence index children. It terminates when it reaches the end of the given sequence. remove the comment to take an input from the user printEnter the elements sequence listmapint, input.split
from __future__ import annotations def generate_all_permutations(sequence: list[int | str]) -> None: create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))]) def create_state_space_tree( sequence: list[int | str], current_sequence: list[int | str], index: int, index_used: list[int], ) -> None: """ Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly len(sequence) - index children. It terminates when it reaches the end of the given sequence. """ if index == len(sequence): print(current_sequence) return for i in range(len(sequence)): if not index_used[i]: current_sequence.append(sequence[i]) index_used[i] = True create_state_space_tree(sequence, current_sequence, index + 1, index_used) current_sequence.pop() index_used[i] = False """ remove the comment to take an input from the user print("Enter the elements") sequence = list(map(int, input().split())) """ sequence: list[int | str] = [3, 1, 2, 4] generate_all_permutations(sequence) sequence_2: list[int | str] = ["A", "B", "C"] generate_all_permutations(sequence_2)
In this problem, we want to determine all possible subsequences of the given sequence. We use backtracking to solve this problem. Time complexity: O2n, where n denotes the length of the given sequence. Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly two children. It terminates when it reaches the end of the given sequence.
from __future__ import annotations from typing import Any def generate_all_subsequences(sequence: list[Any]) -> None: create_state_space_tree(sequence, [], 0) def create_state_space_tree( sequence: list[Any], current_subsequence: list[Any], index: int ) -> None: """ Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly two children. It terminates when it reaches the end of the given sequence. """ if index == len(sequence): print(current_subsequence) return create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.append(sequence[index]) create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.pop() if __name__ == "__main__": seq: list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
Graph Coloring also called m coloring problem consists of coloring a given graph with at most m colors such that no adjacent vertices are assigned the same color Wikipedia: https:en.wikipedia.orgwikiGraphcoloring For each neighbour check if the coloring constraint is satisfied If any of the neighbours fail the constraint return False If all neighbours validate the constraint return True neighbours 0,1,0,1,0 coloredvertices 0, 2, 1, 2, 0 color 1 validcoloringneighbours, coloredvertices, color True color 2 validcoloringneighbours, coloredvertices, color False Does any neighbour not satisfy the constraints PseudoCode Base Case: 1. Check if coloring is complete 1.1 If complete return True meaning that we successfully colored the graph Recursive Step: 2. Iterates over each color: Check if the current coloring is valid: 2.1. Color given vertex 2.2. Do recursive call, check if this coloring leads to a solution 2.4. if current coloring leads to a solution return 2.5. Uncolor given vertex graph 0, 1, 0, 0, 0, ... 1, 0, 1, 0, 1, ... 0, 1, 0, 1, 0, ... 0, 1, 1, 0, 0, ... 0, 1, 0, 0, 0 maxcolors 3 coloredvertices 0, 1, 0, 0, 0 index 3 utilcolorgraph, maxcolors, coloredvertices, index True maxcolors 2 utilcolorgraph, maxcolors, coloredvertices, index False Base Case Recursive Step Color current vertex Validate coloring Backtrack Wrapper function to call subroutine called utilcolor which will either return True or False. If True is returned coloredvertices list is filled with correct colorings graph 0, 1, 0, 0, 0, ... 1, 0, 1, 0, 1, ... 0, 1, 0, 1, 0, ... 0, 1, 1, 0, 0, ... 0, 1, 0, 0, 0 maxcolors 3 colorgraph, maxcolors 0, 1, 0, 2, 0 maxcolors 2 colorgraph, maxcolors
def valid_coloring( neighbours: list[int], colored_vertices: list[int], color: int ) -> bool: """ For each neighbour check if the coloring constraint is satisfied If any of the neighbours fail the constraint return False If all neighbours validate the constraint return True >>> neighbours = [0,1,0,1,0] >>> colored_vertices = [0, 2, 1, 2, 0] >>> color = 1 >>> valid_coloring(neighbours, colored_vertices, color) True >>> color = 2 >>> valid_coloring(neighbours, colored_vertices, color) False """ # Does any neighbour not satisfy the constraints return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(neighbours) ) def util_color( graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int ) -> bool: """ Pseudo-Code Base Case: 1. Check if coloring is complete 1.1 If complete return True (meaning that we successfully colored the graph) Recursive Step: 2. Iterates over each color: Check if the current coloring is valid: 2.1. Color given vertex 2.2. Do recursive call, check if this coloring leads to a solution 2.4. if current coloring leads to a solution return 2.5. Uncolor given vertex >>> graph = [[0, 1, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 1, 0, 1, 0], ... [0, 1, 1, 0, 0], ... [0, 1, 0, 0, 0]] >>> max_colors = 3 >>> colored_vertices = [0, 1, 0, 0, 0] >>> index = 3 >>> util_color(graph, max_colors, colored_vertices, index) True >>> max_colors = 2 >>> util_color(graph, max_colors, colored_vertices, index) False """ # Base Case if index == len(graph): return True # Recursive Step for i in range(max_colors): if valid_coloring(graph[index], colored_vertices, i): # Color current vertex colored_vertices[index] = i # Validate coloring if util_color(graph, max_colors, colored_vertices, index + 1): return True # Backtrack colored_vertices[index] = -1 return False def color(graph: list[list[int]], max_colors: int) -> list[int]: """ Wrapper function to call subroutine called util_color which will either return True or False. If True is returned colored_vertices list is filled with correct colorings >>> graph = [[0, 1, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 1, 0, 1, 0], ... [0, 1, 1, 0, 0], ... [0, 1, 0, 0, 0]] >>> max_colors = 3 >>> color(graph, max_colors) [0, 1, 0, 2, 0] >>> max_colors = 2 >>> color(graph, max_colors) [] """ colored_vertices = [-1] * len(graph) if util_color(graph, max_colors, colored_vertices, 0): return colored_vertices return []
In the Combination Sum problem, we are given a list consisting of distinct integers. We need to find all the combinations whose sum equals to target given. We can use an element more than one. Time complexityAverage Case: On! Constraints: 1 candidates.length 30 2 candidatesi 40 All elements of candidates are distinct. 1 target 40 A recursive function that searches for possible combinations. Backtracks in case of a bigger current combination value than the target value. Parameters previousindex: Last index from the previous search target: The value we need to obtain by summing our integers in the path list. answer: A list of possible combinations path: Current combination candidates: A list of integers we can use. combinationsum2, 3, 5, 8 2, 2, 2, 2, 2, 3, 3, 3, 5 combinationsum2, 3, 6, 7, 7 2, 2, 3, 7 combinationsum8, 2.3, 0, 1 Traceback most recent call last: ... RecursionError: maximum recursion depth exceeded
def backtrack( candidates: list, path: list, answer: list, target: int, previous_index: int ) -> None: """ A recursive function that searches for possible combinations. Backtracks in case of a bigger current combination value than the target value. Parameters ---------- previous_index: Last index from the previous search target: The value we need to obtain by summing our integers in the path list. answer: A list of possible combinations path: Current combination candidates: A list of integers we can use. """ if target == 0: answer.append(path.copy()) else: for index in range(previous_index, len(candidates)): if target >= candidates[index]: path.append(candidates[index]) backtrack(candidates, path, answer, target - candidates[index], index) path.pop(len(path) - 1) def combination_sum(candidates: list, target: int) -> list: """ >>> combination_sum([2, 3, 5], 8) [[2, 2, 2, 2], [2, 3, 3], [3, 5]] >>> combination_sum([2, 3, 6, 7], 7) [[2, 2, 3], [7]] >>> combination_sum([-8, 2.3, 0], 1) Traceback (most recent call last): ... RecursionError: maximum recursion depth exceeded """ path = [] # type: list[int] answer = [] # type: list[int] backtrack(candidates, path, answer, target, 0) return answer def main() -> None: print(combination_sum([-8, 2.3, 0], 1)) if __name__ == "__main__": import doctest doctest.testmod() main()
https:www.geeksforgeeks.orgsolvecrosswordpuzzle Check if a word can be placed at the given position. puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... isvalidpuzzle, 'word', 0, 0, True True puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... isvalidpuzzle, 'word', 0, 0, False True Place a word at the given position. puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... placewordpuzzle, 'word', 0, 0, True puzzle 'w', '', '', '', 'o', '', '', '', 'r', '', '', '', 'd', '', '', '' Remove a word from the given position. puzzle ... 'w', '', '', '', ... 'o', '', '', '', ... 'r', '', '', '', ... 'd', '', '', '' ... removewordpuzzle, 'word', 0, 0, True puzzle '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '' Solve the crossword puzzle using backtracking. puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... words 'word', 'four', 'more', 'last' solvecrosswordpuzzle, words True puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... words 'word', 'four', 'more', 'paragraphs' solvecrosswordpuzzle, words False
# https://www.geeksforgeeks.org/solve-crossword-puzzle/ def is_valid( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> bool: """ Check if a word can be placed at the given position. >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> is_valid(puzzle, 'word', 0, 0, True) True >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> is_valid(puzzle, 'word', 0, 0, False) True """ for i in range(len(word)): if vertical: if row + i >= len(puzzle) or puzzle[row + i][col] != "": return False else: if col + i >= len(puzzle[0]) or puzzle[row][col + i] != "": return False return True def place_word( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> None: """ Place a word at the given position. >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> place_word(puzzle, 'word', 0, 0, True) >>> puzzle [['w', '', '', ''], ['o', '', '', ''], ['r', '', '', ''], ['d', '', '', '']] """ for i, char in enumerate(word): if vertical: puzzle[row + i][col] = char else: puzzle[row][col + i] = char def remove_word( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> None: """ Remove a word from the given position. >>> puzzle = [ ... ['w', '', '', ''], ... ['o', '', '', ''], ... ['r', '', '', ''], ... ['d', '', '', ''] ... ] >>> remove_word(puzzle, 'word', 0, 0, True) >>> puzzle [['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']] """ for i in range(len(word)): if vertical: puzzle[row + i][col] = "" else: puzzle[row][col + i] = "" def solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool: """ Solve the crossword puzzle using backtracking. >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> words = ['word', 'four', 'more', 'last'] >>> solve_crossword(puzzle, words) True >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> words = ['word', 'four', 'more', 'paragraphs'] >>> solve_crossword(puzzle, words) False """ for row in range(len(puzzle)): for col in range(len(puzzle[0])): if puzzle[row][col] == "": for word in words: for vertical in [True, False]: if is_valid(puzzle, word, row, col, vertical): place_word(puzzle, word, row, col, vertical) words.remove(word) if solve_crossword(puzzle, words): return True words.append(word) remove_word(puzzle, word, row, col, vertical) return False return True if __name__ == "__main__": PUZZLE = [[""] * 3 for _ in range(3)] WORDS = ["cat", "dog", "car"] if solve_crossword(PUZZLE, WORDS): print("Solution found:") for row in PUZZLE: print(" ".join(row)) else: print("No solution found:")
author: Aayush Soni Given n pairs of parentheses, write a function to generate all combinations of wellformed parentheses. Input: n 2 Output: , Leetcode link: https:leetcode.comproblemsgenerateparenthesesdescription Generate valid combinations of balanced parentheses using recursion. :param partial: A string representing the current combination. :param opencount: An integer representing the count of open parentheses. :param closecount: An integer representing the count of close parentheses. :param n: An integer representing the total number of pairs. :param result: A list to store valid combinations. :return: None This function uses recursion to explore all possible combinations, ensuring that at each step, the parentheses remain balanced. Example: result backtrack, 0, 0, 2, result result '', '' When the combination is complete, add it to the result. If we can add an open parenthesis, do so, and recurse. If we can add a close parenthesis it won't make the combination invalid, do so, and recurse. Generate valid combinations of balanced parentheses for a given n. :param n: An integer representing the number of pairs of parentheses. :return: A list of strings with valid combinations. This function uses a recursive approach to generate the combinations. Time Complexity: O22n In the worst case, we have 22n combinations. Space Complexity: On where 'n' is the number of pairs. Example 1: generateparenthesis3 '', '', '', '', '' Example 2: generateparenthesis1 ''
def backtrack( partial: str, open_count: int, close_count: int, n: int, result: list[str] ) -> None: """ Generate valid combinations of balanced parentheses using recursion. :param partial: A string representing the current combination. :param open_count: An integer representing the count of open parentheses. :param close_count: An integer representing the count of close parentheses. :param n: An integer representing the total number of pairs. :param result: A list to store valid combinations. :return: None This function uses recursion to explore all possible combinations, ensuring that at each step, the parentheses remain balanced. Example: >>> result = [] >>> backtrack("", 0, 0, 2, result) >>> result ['(())', '()()'] """ if len(partial) == 2 * n: # When the combination is complete, add it to the result. result.append(partial) return if open_count < n: # If we can add an open parenthesis, do so, and recurse. backtrack(partial + "(", open_count + 1, close_count, n, result) if close_count < open_count: # If we can add a close parenthesis (it won't make the combination invalid), # do so, and recurse. backtrack(partial + ")", open_count, close_count + 1, n, result) def generate_parenthesis(n: int) -> list[str]: """ Generate valid combinations of balanced parentheses for a given n. :param n: An integer representing the number of pairs of parentheses. :return: A list of strings with valid combinations. This function uses a recursive approach to generate the combinations. Time Complexity: O(2^(2n)) - In the worst case, we have 2^(2n) combinations. Space Complexity: O(n) - where 'n' is the number of pairs. Example 1: >>> generate_parenthesis(3) ['((()))', '(()())', '(())()', '()(())', '()()()'] Example 2: >>> generate_parenthesis(1) ['()'] """ result: list[str] = [] backtrack("", 0, 0, n, result) return result if __name__ == "__main__": import doctest doctest.testmod()
A Hamiltonian cycle Hamiltonian circuit is a graph cycle through a graph that visits each node exactly once. Determining whether such paths and cycles exist in graphs is the 'Hamiltonian path problem', which is NPcomplete. Wikipedia: https:en.wikipedia.orgwikiHamiltonianpath Checks whether it is possible to add next into path by validating 2 statements 1. There should be path between current and next vertex 2. Next vertex should not be in path If both validations succeed we return True, saying that it is possible to connect this vertices, otherwise we return False Case 1:Use exact graph as in main function, with initialized values graph 0, 1, 0, 1, 0, ... 1, 0, 1, 1, 1, ... 0, 1, 0, 0, 1, ... 1, 1, 0, 0, 1, ... 0, 1, 1, 1, 0 path 0, 1, 1, 1, 1, 0 currind 1 nextver 1 validconnectiongraph, nextver, currind, path True Case 2: Same graph, but trying to connect to node that is already in path path 0, 1, 2, 4, 1, 0 currind 4 nextver 1 validconnectiongraph, nextver, currind, path False 1. Validate that path exists between current and next vertices 2. Validate that next vertex is not already in path PseudoCode Base Case: 1. Check if we visited all of vertices 1.1 If last visited vertex has path to starting vertex return True either return False Recursive Step: 2. Iterate over each vertex Check if next vertex is valid for transiting from current vertex 2.1 Remember next vertex as next transition 2.2 Do recursive call and check if going to this vertex solves problem 2.3 If next vertex leads to solution return True 2.4 Else backtrack, delete remembered vertex Case 1: Use exact graph as in main function, with initialized values graph 0, 1, 0, 1, 0, ... 1, 0, 1, 1, 1, ... 0, 1, 0, 0, 1, ... 1, 1, 0, 0, 1, ... 0, 1, 1, 1, 0 path 0, 1, 1, 1, 1, 0 currind 1 utilhamiltoncyclegraph, path, currind True path 0, 1, 2, 4, 3, 0 Case 2: Use exact graph as in previous case, but in the properties taken from middle of calculation graph 0, 1, 0, 1, 0, ... 1, 0, 1, 1, 1, ... 0, 1, 0, 0, 1, ... 1, 1, 0, 0, 1, ... 0, 1, 1, 1, 0 path 0, 1, 2, 1, 1, 0 currind 3 utilhamiltoncyclegraph, path, currind True path 0, 1, 2, 4, 3, 0 Base Case return whether path exists between current and starting vertices Recursive Step Insert current vertex into path as next transition Validate created path Backtrack Initialize path with 1, indicating that we have not visited them yet path 1 lengraph 1 initialize start and end of path with starting index path0 path1 startindex evaluate and if we find answer return path either return empty array return path if utilhamiltoncyclegraph, path, 1 else
def valid_connection( graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int] ) -> bool: """ Checks whether it is possible to add next into path by validating 2 statements 1. There should be path between current and next vertex 2. Next vertex should not be in path If both validations succeed we return True, saying that it is possible to connect this vertices, otherwise we return False Case 1:Use exact graph as in main function, with initialized values >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, -1, -1, -1, -1, 0] >>> curr_ind = 1 >>> next_ver = 1 >>> valid_connection(graph, next_ver, curr_ind, path) True Case 2: Same graph, but trying to connect to node that is already in path >>> path = [0, 1, 2, 4, -1, 0] >>> curr_ind = 4 >>> next_ver = 1 >>> valid_connection(graph, next_ver, curr_ind, path) False """ # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path) def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool: """ Pseudo-Code Base Case: 1. Check if we visited all of vertices 1.1 If last visited vertex has path to starting vertex return True either return False Recursive Step: 2. Iterate over each vertex Check if next vertex is valid for transiting from current vertex 2.1 Remember next vertex as next transition 2.2 Do recursive call and check if going to this vertex solves problem 2.3 If next vertex leads to solution return True 2.4 Else backtrack, delete remembered vertex Case 1: Use exact graph as in main function, with initialized values >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, -1, -1, -1, -1, 0] >>> curr_ind = 1 >>> util_hamilton_cycle(graph, path, curr_ind) True >>> path [0, 1, 2, 4, 3, 0] Case 2: Use exact graph as in previous case, but in the properties taken from middle of calculation >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, 1, 2, -1, -1, 0] >>> curr_ind = 3 >>> util_hamilton_cycle(graph, path, curr_ind) True >>> path [0, 1, 2, 4, 3, 0] """ # Base Case if curr_ind == len(graph): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(len(graph)): if valid_connection(graph, next_ver, curr_ind, path): # Insert current vertex into path as next transition path[curr_ind] = next_ver # Validate created path if util_hamilton_cycle(graph, path, curr_ind + 1): return True # Backtrack path[curr_ind] = -1 return False def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]: r""" Wrapper function to call subroutine called util_hamilton_cycle, which will either return array of vertices indicating hamiltonian cycle or an empty list indicating that hamiltonian cycle was not found. Case 1: Following graph consists of 5 edges. If we look closely, we can see that there are multiple Hamiltonian cycles. For example one result is when we iterate like: (0)->(1)->(2)->(4)->(3)->(0) (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3)---------(4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> hamilton_cycle(graph) [0, 1, 2, 4, 3, 0] Case 2: Same Graph as it was in Case 1, changed starting index from default to 3 (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3)---------(4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> hamilton_cycle(graph, 3) [3, 0, 1, 2, 4, 3] Case 3: Following Graph is exactly what it was before, but edge 3-4 is removed. Result is that there is no Hamiltonian Cycle anymore. (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3) (4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 0], ... [0, 1, 1, 0, 0]] >>> hamilton_cycle(graph,4) [] """ # Initialize path with -1, indicating that we have not visited them yet path = [-1] * (len(graph) + 1) # initialize start and end of path with starting index path[0] = path[-1] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(graph, path, 1) else []
Knight Tour Intro: https:www.youtube.comwatch?vabdY3dZFHM Find all the valid positions a knight can move to from the current position. getvalidpos1, 3, 4 2, 1, 0, 1, 3, 2 Check if the board matrix has been completely filled with nonzero values. iscomplete1 True iscomplete1, 2, 3, 0 False Helper function to solve knight tour problem. Find the solution for the knight tour problem for a board of size n. Raises ValueError if the tour cannot be performed for the given size. openknighttour1 1 openknighttour2 Traceback most recent call last: ... ValueError: Open Knight Tour cannot be performed on a board of size 2
# Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM from __future__ import annotations def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]: """ Find all the valid positions a knight can move to from the current position. >>> get_valid_pos((1, 3), 4) [(2, 1), (0, 1), (3, 2)] """ y, x = position positions = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] permissible_positions = [] for position in positions: y_test, x_test = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(position) return permissible_positions def is_complete(board: list[list[int]]) -> bool: """ Check if the board (matrix) has been completely filled with non-zero values. >>> is_complete([[1]]) True >>> is_complete([[1, 2], [3, 0]]) False """ return not any(elem == 0 for row in board for elem in row) def open_knight_tour_helper( board: list[list[int]], pos: tuple[int, int], curr: int ) -> bool: """ Helper function to solve knight tour problem. """ if is_complete(board): return True for position in get_valid_pos(pos, len(board)): y, x = position if board[y][x] == 0: board[y][x] = curr + 1 if open_knight_tour_helper(board, position, curr + 1): return True board[y][x] = 0 return False def open_knight_tour(n: int) -> list[list[int]]: """ Find the solution for the knight tour problem for a board of size n. Raises ValueError if the tour cannot be performed for the given size. >>> open_knight_tour(1) [[1]] >>> open_knight_tour(2) Traceback (most recent call last): ... ValueError: Open Knight Tour cannot be performed on a board of size 2 """ board = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): board[i][j] = 1 if open_knight_tour_helper(board, (i, j), 1): return board board[i][j] = 0 msg = f"Open Knight Tour cannot be performed on a board of size {n}" raise ValueError(msg) if __name__ == "__main__": import doctest doctest.testmod()
Determine if a given pattern matches a string using backtracking. pattern: The pattern to match. inputstring: The string to match against the pattern. return: True if the pattern matches the string, False otherwise. matchwordpatternaba, GraphTreesGraph True matchwordpatternxyx, PythonRubyPython True matchwordpatternGG, PythonJavaPython False backtrack0, 0 True backtrack0, 1 True backtrack0, 4 False
def match_word_pattern(pattern: str, input_string: str) -> bool: """ Determine if a given pattern matches a string using backtracking. pattern: The pattern to match. input_string: The string to match against the pattern. return: True if the pattern matches the string, False otherwise. >>> match_word_pattern("aba", "GraphTreesGraph") True >>> match_word_pattern("xyx", "PythonRubyPython") True >>> match_word_pattern("GG", "PythonJavaPython") False """ def backtrack(pattern_index: int, str_index: int) -> bool: """ >>> backtrack(0, 0) True >>> backtrack(0, 1) True >>> backtrack(0, 4) False """ if pattern_index == len(pattern) and str_index == len(input_string): return True if pattern_index == len(pattern) or str_index == len(input_string): return False char = pattern[pattern_index] if char in pattern_map: mapped_str = pattern_map[char] if input_string.startswith(mapped_str, str_index): return backtrack(pattern_index + 1, str_index + len(mapped_str)) else: return False for end in range(str_index + 1, len(input_string) + 1): substr = input_string[str_index:end] if substr in str_map: continue pattern_map[char] = substr str_map[substr] = char if backtrack(pattern_index + 1, end): return True del pattern_map[char] del str_map[substr] return False pattern_map: dict[str, str] = {} str_map: dict[str, str] = {} return backtrack(0, 0) if __name__ == "__main__": import doctest doctest.testmod()
Minimax helps to achieve maximum score in a game by checking all possible moves depth is current depth in game tree. nodeIndex is index of current node in scores. if move is of maximizer return true else false leaves of game tree is stored in scores height is maximum height of Game tree This function implements the minimax algorithm, which helps achieve the optimal score for a player in a twoplayer game by checking all possible moves. If the player is the maximizer, then the score is maximized. If the player is the minimizer, then the score is minimized. Parameters: depth: Current depth in the game tree. nodeindex: Index of the current node in the scores list. ismax: A boolean indicating whether the current move is for the maximizer True or minimizer False. scores: A list containing the scores of the leaves of the game tree. height: The maximum height of the game tree. Returns: An integer representing the optimal score for the current player. import math scores 90, 23, 6, 33, 21, 65, 123, 34423 height math.loglenscores, 2 minimax0, 0, True, scores, height 65 minimax1, 0, True, scores, height Traceback most recent call last: ... ValueError: Depth cannot be less than 0 minimax0, 0, True, , 2 Traceback most recent call last: ... ValueError: Scores cannot be empty scores 3, 5, 2, 9, 12, 5, 23, 23 height math.loglenscores, 2 minimax0, 0, True, scores, height 12 Base case: If the current depth equals the height of the tree, return the score of the current node. If it's the maximizer's turn, choose the maximum score between the two possible moves. If it's the minimizer's turn, choose the minimum score between the two possible moves. Sample scores and height calculation Calculate and print the optimal value using the minimax algorithm
from __future__ import annotations import math def minimax( depth: int, node_index: int, is_max: bool, scores: list[int], height: float ) -> int: """ This function implements the minimax algorithm, which helps achieve the optimal score for a player in a two-player game by checking all possible moves. If the player is the maximizer, then the score is maximized. If the player is the minimizer, then the score is minimized. Parameters: - depth: Current depth in the game tree. - node_index: Index of the current node in the scores list. - is_max: A boolean indicating whether the current move is for the maximizer (True) or minimizer (False). - scores: A list containing the scores of the leaves of the game tree. - height: The maximum height of the game tree. Returns: - An integer representing the optimal score for the current player. >>> import math >>> scores = [90, 23, 6, 33, 21, 65, 123, 34423] >>> height = math.log(len(scores), 2) >>> minimax(0, 0, True, scores, height) 65 >>> minimax(-1, 0, True, scores, height) Traceback (most recent call last): ... ValueError: Depth cannot be less than 0 >>> minimax(0, 0, True, [], 2) Traceback (most recent call last): ... ValueError: Scores cannot be empty >>> scores = [3, 5, 2, 9, 12, 5, 23, 23] >>> height = math.log(len(scores), 2) >>> minimax(0, 0, True, scores, height) 12 """ if depth < 0: raise ValueError("Depth cannot be less than 0") if len(scores) == 0: raise ValueError("Scores cannot be empty") # Base case: If the current depth equals the height of the tree, # return the score of the current node. if depth == height: return scores[node_index] # If it's the maximizer's turn, choose the maximum score # between the two possible moves. if is_max: return max( minimax(depth + 1, node_index * 2, False, scores, height), minimax(depth + 1, node_index * 2 + 1, False, scores, height), ) # If it's the minimizer's turn, choose the minimum score # between the two possible moves. return min( minimax(depth + 1, node_index * 2, True, scores, height), minimax(depth + 1, node_index * 2 + 1, True, scores, height), ) def main() -> None: # Sample scores and height calculation scores = [90, 23, 6, 33, 21, 65, 123, 34423] height = math.log(len(scores), 2) # Calculate and print the optimal value using the minimax algorithm print("Optimal value : ", end="") print(minimax(0, 0, True, scores, height)) if __name__ == "__main__": import doctest doctest.testmod() main()
The nqueens problem is of placing N queens on a N N chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. This function returns a boolean value True if it is safe to place a queen there considering the current state of the board. Parameters: board 2D matrix: The chessboard row, column: Coordinates of the cell on the board Returns: Boolean Value issafe0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 True issafe1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 False Check if there is any queen in the same row, column, left upper diagonal, and right upper diagonal This function creates a state space tree and calls the safe function until it receives a False Boolean and terminates that branch and backtracks to the next possible solution branch. If the row number exceeds N, we have a board with a successful combination and that combination is appended to the solution list and the board is printed. For every row, it iterates through each column to check if it is feasible to place a queen there. If all the combinations for that particular branch are successful, the board is reinitialized for the next possible combination. Prints the boards that have a successful combination. Number of queens e.g., n8 for an 8x8 board
from __future__ import annotations solution = [] def is_safe(board: list[list[int]], row: int, column: int) -> bool: """ This function returns a boolean value True if it is safe to place a queen there considering the current state of the board. Parameters: board (2D matrix): The chessboard row, column: Coordinates of the cell on the board Returns: Boolean Value >>> is_safe([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1) True >>> is_safe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1) False """ n = len(board) # Size of the board # Check if there is any queen in the same row, column, # left upper diagonal, and right upper diagonal return ( all(board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, n))) and all( board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, -1, -1)) ) and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, n))) and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, -1, -1))) ) def solve(board: list[list[int]], row: int) -> bool: """ This function creates a state space tree and calls the safe function until it receives a False Boolean and terminates that branch and backtracks to the next possible solution branch. """ if row >= len(board): """ If the row number exceeds N, we have a board with a successful combination and that combination is appended to the solution list and the board is printed. """ solution.append(board) printboard(board) print() return True for i in range(len(board)): """ For every row, it iterates through each column to check if it is feasible to place a queen there. If all the combinations for that particular branch are successful, the board is reinitialized for the next possible combination. """ if is_safe(board, row, i): board[row][i] = 1 solve(board, row + 1) board[row][i] = 0 return False def printboard(board: list[list[int]]) -> None: """ Prints the boards that have a successful combination. """ for i in range(len(board)): for j in range(len(board)): if board[i][j] == 1: print("Q", end=" ") # Queen is present else: print(".", end=" ") # Empty cell print() # Number of queens (e.g., n=8 for an 8x8 board) n = 8 board = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print("The total number of solutions are:", len(solution))
from future import annotations def depthfirstsearch possibleboard: listint, diagonalrightcollisions: listint, diagonalleftcollisions: listint, boards: listliststr, n: int, None: Get next row in the current board possibleboard to fill it with a queen row lenpossibleboard If row is equal to the size of the board it means there are a queen in each row in the current board possibleboard if row n: We convert the variable possibleboard that looks like this: 1, 3, 0, 2 to this: '. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . ' boards.append. i Q . n 1 i for i in possibleboard return We iterate each column in the row to find all possible results in each row for col in rangen: We apply that we learned previously. First we check that in the current board possibleboard there are not other same value because if there is it means that there are a collision in vertical. Then we apply the two formulas we learned before: 45: y x b or 45: row col b 135: y x b or row col b. And we verify if the results of this two formulas not exist in their variables respectively. diagonalrightcollisions, diagonalleftcollisions If any or these are True it means there is a collision so we continue to the next value in the for loop. if col in possibleboard or row col in diagonalrightcollisions or row col in diagonalleftcollisions : continue If it is False we call dfs function again and we update the inputs depthfirstsearch possibleboard, col, diagonalrightcollisions, row col, diagonalleftcollisions, row col, boards, n, def nqueenssolutionn: int None: boards: listliststr depthfirstsearch, , , boards, n Print all the boards for board in boards: for column in board: printcolumn print printlenboards, solutions were found. if name main: import doctest doctest.testmod nqueenssolution4
r""" Problem: The n queens problem is: placing N queens on a N * N chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. Solution: To solve this problem we will use simple math. First we know the queen can move in all the possible ways, we can simplify it in this: vertical, horizontal, diagonal left and diagonal right. We can visualize it like this: left diagonal = \ right diagonal = / On a chessboard vertical movement could be the rows and horizontal movement could be the columns. In programming we can use an array, and in this array each index could be the rows and each value in the array could be the column. For example: . Q . . We have this chessboard with one queen in each column and each queen . . . Q can't attack to each other. Q . . . The array for this example would look like this: [1, 3, 0, 2] . . Q . So if we use an array and we verify that each value in the array is different to each other we know that at least the queens can't attack each other in horizontal and vertical. At this point we have it halfway completed and we will treat the chessboard as a Cartesian plane. Hereinafter we are going to remember basic math, so in the school we learned this formula: Slope of a line: y2 - y1 m = ---------- x2 - x1 This formula allow us to get the slope. For the angles 45º (right diagonal) and 135º (left diagonal) this formula gives us m = 1, and m = -1 respectively. See:: https://www.enotes.com/homework-help/write-equation-line-that-hits-origin-45-degree-1474860 Then we have this other formula: Slope intercept: y = mx + b b is where the line crosses the Y axis (to get more information see: https://www.mathsisfun.com/y_intercept.html), if we change the formula to solve for b we would have: y - mx = b And since we already have the m values for the angles 45º and 135º, this formula would look like this: 45º: y - (1)x = b 45º: y - x = b 135º: y - (-1)x = b 135º: y + x = b y = row x = column Applying these two formulas we can check if a queen in some position is being attacked for another one or vice versa. """ from __future__ import annotations def depth_first_search( possible_board: list[int], diagonal_right_collisions: list[int], diagonal_left_collisions: list[int], boards: list[list[str]], n: int, ) -> None: """ >>> boards = [] >>> depth_first_search([], [], [], boards, 4) >>> for board in boards: ... print(board) ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] ['. . Q . ', 'Q . . . ', '. . . Q ', '. Q . . '] """ # Get next row in the current board (possible_board) to fill it with a queen row = len(possible_board) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append([". " * i + "Q " + ". " * (n - 1 - i) for i in possible_board]) return # We iterate each column in the row to find all possible results in each row for col in range(n): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col], [*diagonal_right_collisions, row - col], [*diagonal_left_collisions, row + col], boards, n, ) def n_queens_solution(n: int) -> None: boards: list[list[str]] = [] depth_first_search([], [], [], boards, n) # Print all the boards for board in boards: for column in board: print(column) print("") print(len(boards), "solutions were found.") if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
Problem source: https:www.hackerrank.comchallengesthepowersumproblem Find the number of ways that a given integer X, can be expressed as the sum of the Nth powers of unique, natural numbers. For example, if X13 and N2. We have to find all combinations of unique squares adding up to 13. The only solution is 2232. Constraints: 1X1000, 2N10. backtrack13, 2, 1, 0, 0 0, 1 backtrack10, 2, 1, 0, 0 0, 1 backtrack10, 3, 1, 0, 0 0, 0 backtrack20, 2, 1, 0, 0 0, 1 backtrack15, 10, 1, 0, 0 0, 0 backtrack16, 2, 1, 0, 0 0, 1 backtrack20, 1, 1, 0, 0 0, 64 If the sum of the powers is equal to neededsum, then we have a solution. If the sum of the powers is less than neededsum, then continue adding powers. If the power of i is less than neededsum, then try with the next power. solve13, 2 1 solve10, 2 1 solve10, 3 0 solve20, 2 1 solve15, 10 0 solve16, 2 1 solve20, 1 Traceback most recent call last: ... ValueError: Invalid input neededsum must be between 1 and 1000, power between 2 and 10. solve10, 5 Traceback most recent call last: ... ValueError: Invalid input neededsum must be between 1 and 1000, power between 2 and 10.
def backtrack( needed_sum: int, power: int, current_number: int, current_sum: int, solutions_count: int, ) -> tuple[int, int]: """ >>> backtrack(13, 2, 1, 0, 0) (0, 1) >>> backtrack(10, 2, 1, 0, 0) (0, 1) >>> backtrack(10, 3, 1, 0, 0) (0, 0) >>> backtrack(20, 2, 1, 0, 0) (0, 1) >>> backtrack(15, 10, 1, 0, 0) (0, 0) >>> backtrack(16, 2, 1, 0, 0) (0, 1) >>> backtrack(20, 1, 1, 0, 0) (0, 64) """ if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count i_to_n = current_number**power if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n current_sum, solutions_count = backtrack( needed_sum, power, current_number + 1, current_sum, solutions_count ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. current_sum, solutions_count = backtrack( needed_sum, power, current_number + 1, current_sum, solutions_count ) return current_sum, solutions_count def solve(needed_sum: int, power: int) -> int: """ >>> solve(13, 2) 1 >>> solve(10, 2) 1 >>> solve(10, 3) 0 >>> solve(20, 2) 1 >>> solve(15, 10) 0 >>> solve(16, 2) 1 >>> solve(20, 1) Traceback (most recent call last): ... ValueError: Invalid input needed_sum must be between 1 and 1000, power between 2 and 10. >>> solve(-10, 5) Traceback (most recent call last): ... ValueError: Invalid input needed_sum must be between 1 and 1000, power between 2 and 10. """ if not (1 <= needed_sum <= 1000 and 2 <= power <= 10): raise ValueError( "Invalid input\n" "needed_sum must be between 1 and 1000, power between 2 and 10." ) return backtrack(needed_sum, power, 1, 0, 0)[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
This method solves the rat in maze problem. Parameters : maze: A two dimensional matrix of zeros and ones. sourcerow: The row index of the starting point. sourcecolumn: The column index of the starting point. destinationrow: The row index of the destination point. destinationcolumn: The column index of the destination point. Returns: solution: A 2D matrix representing the solution path if it exists. Raises: ValueError: If no solution exists or if the source or destination coordinates are invalid. Description: This method navigates through a maze represented as an n by n matrix, starting from a specified source cell and aiming to reach a destination cell. The maze consists of walls 1s and open paths 0s. By providing custom row and column values, the source and destination cells can be adjusted. maze 0, 1, 0, 1, 1, ... 0, 0, 0, 0, 0, ... 1, 0, 1, 0, 1, ... 0, 0, 1, 0, 0, ... 1, 0, 0, 1, 0 solvemazemaze,0,0,lenmaze1,lenmaze1 doctest: NORMALIZEWHITESPACE 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0 Note: In the output maze, the zeros 0s represent one of the possible paths from the source to the destination. maze 0, 1, 0, 1, 1, ... 0, 0, 0, 0, 0, ... 0, 0, 0, 0, 1, ... 0, 0, 0, 0, 0, ... 0, 0, 0, 0, 0 solvemazemaze,0,0,lenmaze1,lenmaze1 doctest: NORMALIZEWHITESPACE 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0 maze 0, 0, 0, ... 0, 1, 0, ... 1, 0, 0 solvemazemaze,0,0,lenmaze1,lenmaze1 doctest: NORMALIZEWHITESPACE 0, 0, 0, 1, 1, 0, 1, 1, 0 maze 1, 0, 0, ... 0, 1, 0, ... 1, 0, 0 solvemazemaze,0,1,lenmaze1,lenmaze1 doctest: NORMALIZEWHITESPACE 1, 0, 0, 1, 1, 0, 1, 1, 0 maze 1, 1, 0, 0, 1, 0, 0, 1, ... 1, 0, 1, 0, 0, 1, 1, 1, ... 0, 1, 0, 1, 0, 0, 1, 0, ... 1, 1, 1, 0, 0, 1, 0, 1, ... 0, 1, 0, 0, 1, 0, 1, 1, ... 0, 0, 0, 1, 1, 1, 0, 1, ... 0, 1, 0, 1, 0, 1, 1, 1, ... 1, 1, 0, 0, 0, 0, 0, 1 solvemazemaze,0,2,lenmaze1,2 doctest: NORMALIZEWHITESPACE 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 maze 1, 0, 0, ... 0, 1, 1, ... 1, 0, 1 solvemazemaze,0,1,lenmaze1,lenmaze1 Traceback most recent call last: ... ValueError: No solution exists! maze 0, 0, ... 1, 1 solvemazemaze,0,0,lenmaze1,lenmaze1 Traceback most recent call last: ... ValueError: No solution exists! maze 0, 1, ... 1, 0 solvemazemaze,2,0,lenmaze1,lenmaze1 Traceback most recent call last: ... ValueError: Invalid source or destination coordinates maze 1, 0, 0, ... 0, 1, 0, ... 1, 0, 0 solvemazemaze,0,1,lenmaze,lenmaze1 Traceback most recent call last: ... ValueError: Invalid source or destination coordinates Check if source and destination coordinates are Invalid. We need to create solution object to save path. This method is recursive starting from i, j and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters maze: A two dimensional matrix of zeros and ones. i, j : coordinates of matrix solutions: A two dimensional matrix of solutions. Returns: Boolean if path is found True, Otherwise False. Final check point. check for already visited and block points. check visited check for directions
from __future__ import annotations def solve_maze( maze: list[list[int]], source_row: int, source_column: int, destination_row: int, destination_column: int, ) -> list[list[int]]: """ This method solves the "rat in maze" problem. Parameters : - maze: A two dimensional matrix of zeros and ones. - source_row: The row index of the starting point. - source_column: The column index of the starting point. - destination_row: The row index of the destination point. - destination_column: The column index of the destination point. Returns: - solution: A 2D matrix representing the solution path if it exists. Raises: - ValueError: If no solution exists or if the source or destination coordinates are invalid. Description: This method navigates through a maze represented as an n by n matrix, starting from a specified source cell and aiming to reach a destination cell. The maze consists of walls (1s) and open paths (0s). By providing custom row and column values, the source and destination cells can be adjusted. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 0, 1, 0, 0], ... [1, 0, 0, 1, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 1, 1, 1, 1], [0, 0, 0, 0, 1], [1, 1, 1, 0, 1], [1, 1, 1, 0, 0], [1, 1, 1, 1, 0]] Note: In the output maze, the zeros (0s) represent one of the possible paths from the source to the destination. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0]] >>> maze = [[0, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 0, 0], [1, 1, 0], [1, 1, 0]] >>> maze = [[1, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[1, 0, 0], [1, 1, 0], [1, 1, 0]] >>> maze = [[1, 1, 0, 0, 1, 0, 0, 1], ... [1, 0, 1, 0, 0, 1, 1, 1], ... [0, 1, 0, 1, 0, 0, 1, 0], ... [1, 1, 1, 0, 0, 1, 0, 1], ... [0, 1, 0, 0, 1, 0, 1, 1], ... [0, 0, 0, 1, 1, 1, 0, 1], ... [0, 1, 0, 1, 0, 1, 1, 1], ... [1, 1, 0, 0, 0, 0, 0, 1]] >>> solve_maze(maze,0,2,len(maze)-1,2) # doctest: +NORMALIZE_WHITESPACE [[1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1]] >>> maze = [[1, 0, 0], ... [0, 1, 1], ... [1, 0, 1]] >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: No solution exists! >>> maze = [[0, 0], ... [1, 1]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: No solution exists! >>> maze = [[0, 1], ... [1, 0]] >>> solve_maze(maze,2,0,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: Invalid source or destination coordinates >>> maze = [[1, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,1,len(maze),len(maze)-1) Traceback (most recent call last): ... ValueError: Invalid source or destination coordinates """ size = len(maze) # Check if source and destination coordinates are Invalid. if not (0 <= source_row <= size - 1 and 0 <= source_column <= size - 1) or ( not (0 <= destination_row <= size - 1 and 0 <= destination_column <= size - 1) ): raise ValueError("Invalid source or destination coordinates") # We need to create solution object to save path. solutions = [[1 for _ in range(size)] for _ in range(size)] solved = run_maze( maze, source_row, source_column, destination_row, destination_column, solutions ) if solved: return solutions else: raise ValueError("No solution exists!") def run_maze( maze: list[list[int]], i: int, j: int, destination_row: int, destination_column: int, solutions: list[list[int]], ) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters maze: A two dimensional matrix of zeros and ones. i, j : coordinates of matrix solutions: A two dimensional matrix of solutions. Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == destination_row and j == destination_column and maze[i][j] == 0: solutions[i][j] = 0 return True lower_flag = (not i < 0) and (not j < 0) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited solutions[i][j] = 0 # check for directions if ( run_maze(maze, i + 1, j, destination_row, destination_column, solutions) or run_maze( maze, i, j + 1, destination_row, destination_column, solutions ) or run_maze( maze, i - 1, j, destination_row, destination_column, solutions ) or run_maze( maze, i, j - 1, destination_row, destination_column, solutions ) ): return True solutions[i][j] = 1 return False return False if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
Given a partially filled 99 2D array, the objective is to fill a 99 square grid with digits numbered 1 to 9, so that every row, column, and and each of the nine 33 subgrids contains all of the digits. This can be solved using Backtracking and is similar to nqueens. We check to see if a cell is safe or not and recursively call the function on the next column to see if it returns True. if yes, we have solved the puzzle. else, we backtrack and place another number in that cell and repeat this process. assigning initial values to the grid a grid with no solution This function checks the grid to see if each row, column, and the 3x3 subgrids contain the digit 'n'. It returns False if it is not 'safe' a duplicate digit is found else returns True if it is 'safe' This function finds an empty location so that we can assign a number for that particular row and column. Takes a partially filledin grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution nonduplication across rows, columns, and boxes sudokuinitialgrid doctest: NORMALIZEWHITESPACE 3, 1, 6, 5, 7, 8, 4, 9, 2, 5, 2, 9, 1, 3, 4, 7, 6, 8, 4, 8, 7, 6, 2, 9, 5, 3, 1, 2, 6, 3, 4, 1, 5, 9, 8, 7, 9, 7, 4, 8, 6, 3, 1, 2, 5, 8, 5, 1, 7, 9, 2, 6, 4, 3, 1, 3, 8, 9, 4, 7, 2, 5, 6, 6, 9, 2, 3, 5, 1, 8, 7, 4, 7, 4, 5, 2, 8, 6, 3, 1, 9 sudokunosolution is None True If the location is None, then the grid is solved. A function to print the solution in the form of a 9x9 grid make a copy of grid so that you can compare with the unmodified grid
from __future__ import annotations Matrix = list[list[int]] # assigning initial values to the grid initial_grid: Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution no_solution: Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool: """ This function checks the grid to see if each row, column, and the 3x3 subgrids contain the digit 'n'. It returns False if it is not 'safe' (a duplicate digit is found) else returns True if it is 'safe' """ for i in range(9): if n in {grid[row][i], grid[i][column]}: return False for i in range(3): for j in range(3): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def find_empty_location(grid: Matrix) -> tuple[int, int] | None: """ This function finds an empty location so that we can assign a number for that particular row and column. """ for i in range(9): for j in range(9): if grid[i][j] == 0: return i, j return None def sudoku(grid: Matrix) -> Matrix | None: """ Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) >>> sudoku(initial_grid) # doctest: +NORMALIZE_WHITESPACE [[3, 1, 6, 5, 7, 8, 4, 9, 2], [5, 2, 9, 1, 3, 4, 7, 6, 8], [4, 8, 7, 6, 2, 9, 5, 3, 1], [2, 6, 3, 4, 1, 5, 9, 8, 7], [9, 7, 4, 8, 6, 3, 1, 2, 5], [8, 5, 1, 7, 9, 2, 6, 4, 3], [1, 3, 8, 9, 4, 7, 2, 5, 6], [6, 9, 2, 3, 5, 1, 8, 7, 4], [7, 4, 5, 2, 8, 6, 3, 1, 9]] >>> sudoku(no_solution) is None True """ if location := find_empty_location(grid): row, column = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1, 10): if is_safe(grid, row, column, digit): grid[row][column] = digit if sudoku(grid) is not None: return grid grid[row][column] = 0 return None def print_solution(grid: Matrix) -> None: """ A function to print the solution in the form of a 9x9 grid """ for row in grid: for cell in row: print(cell, end=" ") print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") solution = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
The sumofsubsetsproblem states that a set of nonnegative integers, and a value M, determine all possible subsets of the given set whose summation sum equal to given M. Summation of the chosen numbers must be equal to given number M and one number can be used only once. Creates a state space tree to iterate through each branch using DFS. It terminates the branching of a node when any of the two conditions given below satisfy. This algorithm follows depthfistsearch and backtracks when the node is not branchable. remove the comment to take an input from the user printEnter the elements nums listmapint, input.split printEnter maxsum sum maxsum intinput
from __future__ import annotations def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]: result: list[list[int]] = [] path: list[int] = [] num_index = 0 remaining_nums_sum = sum(nums) create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum) return result def create_state_space_tree( nums: list[int], max_sum: int, num_index: int, path: list[int], result: list[list[int]], remaining_nums_sum: int, ) -> None: """ Creates a state space tree to iterate through each branch using DFS. It terminates the branching of a node when any of the two conditions given below satisfy. This algorithm follows depth-fist-search and backtracks when the node is not branchable. """ if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: result.append(path) return for index in range(num_index, len(nums)): create_state_space_tree( nums, max_sum, index + 1, [*path, nums[index]], result, remaining_nums_sum - nums[index], ) """ remove the comment to take an input from the user print("Enter the elements") nums = list(map(int, input().split())) print("Enter max_sum sum") max_sum = int(input()) """ nums = [3, 34, 4, 12, 5, 2] max_sum = 9 result = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
Author : Alexander Pantyukhin Date : November 24, 2022 Task: Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can 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. Example: Matrix: ABCE SFCS ADEE Word: ABCCED Result: True Implementation notes: Use backtracking approach. At each point, check all neighbors to try to find the next letter of the word. leetcode: https:leetcode.comproblemswordsearch Returns the hash key of matrix indexes. getpointkey10, 20, 1, 0 200 Return True if it's possible to search the word suffix starting from the wordindex. exitswordA, B, 0, 0, 0, set False wordexistsA,B,C,E,S,F,C,S,A,D,E,E, ABCCED True wordexistsA,B,C,E,S,F,C,S,A,D,E,E, SEE True wordexistsA,B,C,E,S,F,C,S,A,D,E,E, ABCB False wordexistsA, A True wordexistsB, A, A, A, A, A, A, B, A, ABB False wordexistsA, 123 Traceback most recent call last: ... ValueError: The word parameter should be a string of length greater than 0. wordexistsA, Traceback most recent call last: ... ValueError: The word parameter should be a string of length greater than 0. wordexists, AB Traceback most recent call last: ... ValueError: The board should be a non empty matrix of single chars strings. wordexists, AB Traceback most recent call last: ... ValueError: The board should be a non empty matrix of single chars strings. wordexistsA, 21, AB Traceback most recent call last: ... ValueError: The board should be a non empty matrix of single chars strings. Validate board Validate word
def get_point_key(len_board: int, len_board_column: int, row: int, column: int) -> int: """ Returns the hash key of matrix indexes. >>> get_point_key(10, 20, 1, 0) 200 """ return len_board * len_board_column * row + column def exits_word( board: list[list[str]], word: str, row: int, column: int, word_index: int, visited_points_set: set[int], ) -> bool: """ Return True if it's possible to search the word suffix starting from the word_index. >>> exits_word([["A"]], "B", 0, 0, 0, set()) False """ if board[row][column] != word[word_index]: return False if word_index == len(word) - 1: return True traverts_directions = [(0, 1), (0, -1), (-1, 0), (1, 0)] len_board = len(board) len_board_column = len(board[0]) for direction in traverts_directions: next_i = row + direction[0] next_j = column + direction[1] if not (0 <= next_i < len_board and 0 <= next_j < len_board_column): continue key = get_point_key(len_board, len_board_column, next_i, next_j) if key in visited_points_set: continue visited_points_set.add(key) if exits_word(board, word, next_i, next_j, word_index + 1, visited_points_set): return True visited_points_set.remove(key) return False def word_exists(board: list[list[str]], word: str) -> bool: """ >>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED") True >>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE") True >>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB") False >>> word_exists([["A"]], "A") True >>> word_exists([["B", "A", "A"], ["A", "A", "A"], ["A", "B", "A"]], "ABB") False >>> word_exists([["A"]], 123) Traceback (most recent call last): ... ValueError: The word parameter should be a string of length greater than 0. >>> word_exists([["A"]], "") Traceback (most recent call last): ... ValueError: The word parameter should be a string of length greater than 0. >>> word_exists([[]], "AB") Traceback (most recent call last): ... ValueError: The board should be a non empty matrix of single chars strings. >>> word_exists([], "AB") Traceback (most recent call last): ... ValueError: The board should be a non empty matrix of single chars strings. >>> word_exists([["A"], [21]], "AB") Traceback (most recent call last): ... ValueError: The board should be a non empty matrix of single chars strings. """ # Validate board board_error_message = ( "The board should be a non empty matrix of single chars strings." ) len_board = len(board) if not isinstance(board, list) or len(board) == 0: raise ValueError(board_error_message) for row in board: if not isinstance(row, list) or len(row) == 0: raise ValueError(board_error_message) for item in row: if not isinstance(item, str) or len(item) != 1: raise ValueError(board_error_message) # Validate word if not isinstance(word, str) or len(word) == 0: raise ValueError( "The word parameter should be a string of length greater than 0." ) len_board_column = len(board[0]) for i in range(len_board): for j in range(len_board_column): if exits_word( board, word, i, j, 0, {get_point_key(len_board, len_board_column, i, j)} ): return True return False if __name__ == "__main__": import doctest doctest.testmod()
https:www.tutorialspoint.compython3bitwiseoperatorsexample.htm Take in 2 integers, convert them to binary, return a binary number that is the result of a binary and operation on the integers provided. binaryand25, 32 '0b000000' binaryand37, 50 '0b100000' binaryand21, 30 '0b10100' binaryand58, 73 '0b0001000' binaryand0, 255 '0b00000000' binaryand256, 256 '0b100000000' binaryand0, 1 Traceback most recent call last: ... ValueError: the value of both inputs must be positive binaryand0, 1.1 Traceback most recent call last: ... TypeError: 'float' object cannot be interpreted as an integer binaryand0, 1 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int'
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_and(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary and operation on the integers provided. >>> binary_and(25, 32) '0b000000' >>> binary_and(37, 50) '0b100000' >>> binary_and(21, 30) '0b10100' >>> binary_and(58, 73) '0b0001000' >>> binary_and(0, 255) '0b00000000' >>> binary_and(256, 256) '0b100000000' >>> binary_and(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_and(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_and("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a == "1" and char_b == "1")) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
Find binary coded decimal bcd of integer base 10. Each digit of the number is represented by a 4bit binary. Example: binarycodeddecimal2 '0b0000' binarycodeddecimal1 '0b0000' binarycodeddecimal0 '0b0000' binarycodeddecimal3 '0b0011' binarycodeddecimal2 '0b0010' binarycodeddecimal12 '0b00010010' binarycodeddecimal987 '0b100110000111'
def binary_coded_decimal(number: int) -> str: """ Find binary coded decimal (bcd) of integer base 10. Each digit of the number is represented by a 4-bit binary. Example: >>> binary_coded_decimal(-2) '0b0000' >>> binary_coded_decimal(-1) '0b0000' >>> binary_coded_decimal(0) '0b0000' >>> binary_coded_decimal(3) '0b0011' >>> binary_coded_decimal(2) '0b0010' >>> binary_coded_decimal(12) '0b00010010' >>> binary_coded_decimal(987) '0b100110000111' """ return "0b" + "".join( str(bin(int(digit)))[2:].zfill(4) for digit in str(max(0, number)) ) if __name__ == "__main__": import doctest doctest.testmod()
Take in 1 integer, return a number that is the number of 1's in binary representation of that number. binarycountsetbits25 3 binarycountsetbits36 2 binarycountsetbits16 1 binarycountsetbits58 4 binarycountsetbits4294967295 32 binarycountsetbits0 0 binarycountsetbits10 Traceback most recent call last: ... ValueError: Input value must be a positive integer binarycountsetbits0.8 Traceback most recent call last: ... TypeError: Input value must be a 'int' type binarycountsetbits0 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int'
def binary_count_setbits(a: int) -> int: """ Take in 1 integer, return a number that is the number of 1's in binary representation of that number. >>> binary_count_setbits(25) 3 >>> binary_count_setbits(36) 2 >>> binary_count_setbits(16) 1 >>> binary_count_setbits(58) 4 >>> binary_count_setbits(4294967295) 32 >>> binary_count_setbits(0) 0 >>> binary_count_setbits(-10) Traceback (most recent call last): ... ValueError: Input value must be a positive integer >>> binary_count_setbits(0.8) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> binary_count_setbits("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return bin(a).count("1") if __name__ == "__main__": import doctest doctest.testmod()
Take in 1 integer, return a number that is the number of trailing zeros in binary representation of that number. binarycounttrailingzeros25 0 binarycounttrailingzeros36 2 binarycounttrailingzeros16 4 binarycounttrailingzeros58 1 binarycounttrailingzeros4294967296 32 binarycounttrailingzeros0 0 binarycounttrailingzeros10 Traceback most recent call last: ... ValueError: Input value must be a positive integer binarycounttrailingzeros0.8 Traceback most recent call last: ... TypeError: Input value must be a 'int' type binarycounttrailingzeros0 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int'
from math import log2 def binary_count_trailing_zeros(a: int) -> int: """ Take in 1 integer, return a number that is the number of trailing zeros in binary representation of that number. >>> binary_count_trailing_zeros(25) 0 >>> binary_count_trailing_zeros(36) 2 >>> binary_count_trailing_zeros(16) 4 >>> binary_count_trailing_zeros(58) 1 >>> binary_count_trailing_zeros(4294967296) 32 >>> binary_count_trailing_zeros(0) 0 >>> binary_count_trailing_zeros(-10) Traceback (most recent call last): ... ValueError: Input value must be a positive integer >>> binary_count_trailing_zeros(0.8) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> binary_count_trailing_zeros("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return 0 if (a == 0) else int(log2(a & -a)) if __name__ == "__main__": import doctest doctest.testmod()
https:www.tutorialspoint.compython3bitwiseoperatorsexample.htm Take in 2 integers, convert them to binary, and return a binary number that is the result of a binary or operation on the integers provided. binaryor25, 32 '0b111001' binaryor37, 50 '0b110111' binaryor21, 30 '0b11111' binaryor58, 73 '0b1111011' binaryor0, 255 '0b11111111' binaryor0, 256 '0b100000000' binaryor0, 1 Traceback most recent call last: ... ValueError: the value of both inputs must be positive binaryor0, 1.1 Traceback most recent call last: ... TypeError: 'float' object cannot be interpreted as an integer binaryor0, 1 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int'
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_or(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, and return a binary number that is the result of a binary or operation on the integers provided. >>> binary_or(25, 32) '0b111001' >>> binary_or(37, 50) '0b110111' >>> binary_or(21, 30) '0b11111' >>> binary_or(58, 73) '0b1111011' >>> binary_or(0, 255) '0b11111111' >>> binary_or(0, 256) '0b100000000' >>> binary_or(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_or(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_or("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int("1" in (char_a, char_b))) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
Information on binary shifts: https:docs.python.org3librarystdtypes.htmlbitwiseoperationsonintegertypes https:www.interviewcake.comconceptjavabitshift Take in 2 positive integers. 'number' is the integer to be logically left shifted 'shiftamount' times. i.e. number shiftamount Return the shifted binary representation. logicalleftshift0, 1 '0b00' logicalleftshift1, 1 '0b10' logicalleftshift1, 5 '0b100000' logicalleftshift17, 2 '0b1000100' logicalleftshift1983, 4 '0b111101111110000' logicalleftshift1, 1 Traceback most recent call last: ... ValueError: both inputs must be positive integers Take in positive 2 integers. 'number' is the integer to be logically right shifted 'shiftamount' times. i.e. number shiftamount Return the shifted binary representation. logicalrightshift0, 1 '0b0' logicalrightshift1, 1 '0b0' logicalrightshift1, 5 '0b0' logicalrightshift17, 2 '0b100' logicalrightshift1983, 4 '0b1111011' logicalrightshift1, 1 Traceback most recent call last: ... ValueError: both inputs must be positive integers Take in 2 integers. 'number' is the integer to be arithmetically right shifted 'shiftamount' times. i.e. number shiftamount Return the shifted binary representation. arithmeticrightshift0, 1 '0b00' arithmeticrightshift1, 1 '0b00' arithmeticrightshift1, 1 '0b11' arithmeticrightshift17, 2 '0b000100' arithmeticrightshift17, 2 '0b111011' arithmeticrightshift1983, 4 '0b111110000100'
# Information on binary shifts: # https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types # https://www.interviewcake.com/concept/java/bit-shift def logical_left_shift(number: int, shift_amount: int) -> str: """ Take in 2 positive integers. 'number' is the integer to be logically left shifted 'shift_amount' times. i.e. (number << shift_amount) Return the shifted binary representation. >>> logical_left_shift(0, 1) '0b00' >>> logical_left_shift(1, 1) '0b10' >>> logical_left_shift(1, 5) '0b100000' >>> logical_left_shift(17, 2) '0b1000100' >>> logical_left_shift(1983, 4) '0b111101111110000' >>> logical_left_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number)) binary_number += "0" * shift_amount return binary_number def logical_right_shift(number: int, shift_amount: int) -> str: """ Take in positive 2 integers. 'number' is the integer to be logically right shifted 'shift_amount' times. i.e. (number >>> shift_amount) Return the shifted binary representation. >>> logical_right_shift(0, 1) '0b0' >>> logical_right_shift(1, 1) '0b0' >>> logical_right_shift(1, 5) '0b0' >>> logical_right_shift(17, 2) '0b100' >>> logical_right_shift(1983, 4) '0b1111011' >>> logical_right_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number))[2:] if shift_amount >= len(binary_number): return "0b0" shifted_binary_number = binary_number[: len(binary_number) - shift_amount] return "0b" + shifted_binary_number def arithmetic_right_shift(number: int, shift_amount: int) -> str: """ Take in 2 integers. 'number' is the integer to be arithmetically right shifted 'shift_amount' times. i.e. (number >> shift_amount) Return the shifted binary representation. >>> arithmetic_right_shift(0, 1) '0b00' >>> arithmetic_right_shift(1, 1) '0b00' >>> arithmetic_right_shift(-1, 1) '0b11' >>> arithmetic_right_shift(17, 2) '0b000100' >>> arithmetic_right_shift(-17, 2) '0b111011' >>> arithmetic_right_shift(-1983, 4) '0b111110000100' """ if number >= 0: # Get binary representation of positive number binary_number = "0" + str(bin(number)).strip("-")[2:] else: # Get binary (2's complement) representation of negative number binary_number_length = len(bin(number)[3:]) # Find 2's complement of number binary_number = bin(abs(number) - (1 << binary_number_length))[3:] binary_number = ( "1" + "0" * (binary_number_length - len(binary_number)) + binary_number ) if shift_amount >= len(binary_number): return "0b" + binary_number[0] * len(binary_number) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(binary_number) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
Information on 2's complement: https:en.wikipedia.orgwikiTwo27scomplement Take in a negative integer 'number'. Return the two's complement representation of 'number'. twoscomplement0 '0b0' twoscomplement1 '0b11' twoscomplement5 '0b1011' twoscomplement17 '0b101111' twoscomplement207 '0b100110001' twoscomplement1 Traceback most recent call last: ... ValueError: input must be a negative integer
# Information on 2's complement: https://en.wikipedia.org/wiki/Two%27s_complement def twos_complement(number: int) -> str: """ Take in a negative integer 'number'. Return the two's complement representation of 'number'. >>> twos_complement(0) '0b0' >>> twos_complement(-1) '0b11' >>> twos_complement(-5) '0b1011' >>> twos_complement(-17) '0b101111' >>> twos_complement(-207) '0b100110001' >>> twos_complement(1) Traceback (most recent call last): ... ValueError: input must be a negative integer """ if number > 0: raise ValueError("input must be a negative integer") binary_number_length = len(bin(number)[3:]) twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:] twos_complement_number = ( ( "1" + "0" * (binary_number_length - len(twos_complement_number)) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
https:www.tutorialspoint.compython3bitwiseoperatorsexample.htm Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. binaryxor25, 32 '0b111001' binaryxor37, 50 '0b010111' binaryxor21, 30 '0b01011' binaryxor58, 73 '0b1110011' binaryxor0, 255 '0b11111111' binaryxor256, 256 '0b000000000' binaryxor0, 1 Traceback most recent call last: ... ValueError: the value of both inputs must be positive binaryxor0, 1.1 Traceback most recent call last: ... TypeError: 'float' object cannot be interpreted as an integer binaryxor0, 1 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int'
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_xor(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>> binary_xor(37, 50) '0b010111' >>> binary_xor(21, 30) '0b01011' >>> binary_xor(58, 73) '0b1110011' >>> binary_xor(0, 255) '0b11111111' >>> binary_xor(256, 256) '0b000000000' >>> binary_xor(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_xor(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_xor("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
Calculates the sum of two nonnegative integers using bitwise operators Wikipedia explanation: https:en.wikipedia.orgwikiBinarynumber bitwiseadditionrecursive4, 5 9 bitwiseadditionrecursive8, 9 17 bitwiseadditionrecursive0, 4 4 bitwiseadditionrecursive4.5, 9 Traceback most recent call last: ... TypeError: Both arguments MUST be integers! bitwiseadditionrecursive'4', 9 Traceback most recent call last: ... TypeError: Both arguments MUST be integers! bitwiseadditionrecursive'4.5', 9 Traceback most recent call last: ... TypeError: Both arguments MUST be integers! bitwiseadditionrecursive1, 9 Traceback most recent call last: ... ValueError: Both arguments MUST be nonnegative! bitwiseadditionrecursive1, 9 Traceback most recent call last: ... ValueError: Both arguments MUST be nonnegative!
def bitwise_addition_recursive(number: int, other_number: int) -> int: """ >>> bitwise_addition_recursive(4, 5) 9 >>> bitwise_addition_recursive(8, 9) 17 >>> bitwise_addition_recursive(0, 4) 4 >>> bitwise_addition_recursive(4.5, 9) Traceback (most recent call last): ... TypeError: Both arguments MUST be integers! >>> bitwise_addition_recursive('4', 9) Traceback (most recent call last): ... TypeError: Both arguments MUST be integers! >>> bitwise_addition_recursive('4.5', 9) Traceback (most recent call last): ... TypeError: Both arguments MUST be integers! >>> bitwise_addition_recursive(-1, 9) Traceback (most recent call last): ... ValueError: Both arguments MUST be non-negative! >>> bitwise_addition_recursive(1, -9) Traceback (most recent call last): ... ValueError: Both arguments MUST be non-negative! """ if not isinstance(number, int) or not isinstance(other_number, int): raise TypeError("Both arguments MUST be integers!") if number < 0 or other_number < 0: raise ValueError("Both arguments MUST be non-negative!") bitwise_sum = number ^ other_number carry = number & other_number if carry == 0: return bitwise_sum return bitwise_addition_recursive(bitwise_sum, carry << 1) if __name__ == "__main__": import doctest doctest.testmod()
Count the number of set bits in a 32 bit integer using Brian Kernighan's way. Ref https:graphics.stanford.eduseanderbithacks.htmlCountBitsSetKernighan get1scount25 3 get1scount37 3 get1scount21 3 get1scount58 4 get1scount0 0 get1scount256 1 get1scount1 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer get1scount0.8 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer get1scount25 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer This way we arrive at next set bit next 1 instead of looping through each bit and checking for 1s hence the loop won't run 32 times it will only run the number of 1 times
def get_1s_count(number: int) -> int: """ Count the number of set bits in a 32 bit integer using Brian Kernighan's way. Ref - https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan >>> get_1s_count(25) 3 >>> get_1s_count(37) 3 >>> get_1s_count(21) 3 >>> get_1s_count(58) 4 >>> get_1s_count(0) 0 >>> get_1s_count(256) 1 >>> get_1s_count(-1) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> get_1s_count(0.8) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> get_1s_count("25") Traceback (most recent call last): ... ValueError: Input must be a non-negative integer """ if not isinstance(number, int) or number < 0: raise ValueError("Input must be a non-negative integer") count = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
Count the number of set bits in a 32 bit integer getsetbitscountusingbriankernighansalgorithm25 3 getsetbitscountusingbriankernighansalgorithm37 3 getsetbitscountusingbriankernighansalgorithm21 3 getsetbitscountusingbriankernighansalgorithm58 4 getsetbitscountusingbriankernighansalgorithm0 0 getsetbitscountusingbriankernighansalgorithm256 1 getsetbitscountusingbriankernighansalgorithm1 Traceback most recent call last: ... ValueError: the value of input must not be negative Count the number of set bits in a 32 bit integer getsetbitscountusingmodulooperator25 3 getsetbitscountusingmodulooperator37 3 getsetbitscountusingmodulooperator21 3 getsetbitscountusingmodulooperator58 4 getsetbitscountusingmodulooperator0 0 getsetbitscountusingmodulooperator256 1 getsetbitscountusingmodulooperator1 Traceback most recent call last: ... ValueError: the value of input must not be negative Benchmark code for comparing 2 functions, with different length int values. Brian Kernighan's algorithm is consistently faster than using modulooperator.
from timeit import timeit def get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int: """ Count the number of set bits in a 32 bit integer >>> get_set_bits_count_using_brian_kernighans_algorithm(25) 3 >>> get_set_bits_count_using_brian_kernighans_algorithm(37) 3 >>> get_set_bits_count_using_brian_kernighans_algorithm(21) 3 >>> get_set_bits_count_using_brian_kernighans_algorithm(58) 4 >>> get_set_bits_count_using_brian_kernighans_algorithm(0) 0 >>> get_set_bits_count_using_brian_kernighans_algorithm(256) 1 >>> get_set_bits_count_using_brian_kernighans_algorithm(-1) Traceback (most recent call last): ... ValueError: the value of input must not be negative """ if number < 0: raise ValueError("the value of input must not be negative") result = 0 while number: number &= number - 1 result += 1 return result def get_set_bits_count_using_modulo_operator(number: int) -> int: """ Count the number of set bits in a 32 bit integer >>> get_set_bits_count_using_modulo_operator(25) 3 >>> get_set_bits_count_using_modulo_operator(37) 3 >>> get_set_bits_count_using_modulo_operator(21) 3 >>> get_set_bits_count_using_modulo_operator(58) 4 >>> get_set_bits_count_using_modulo_operator(0) 0 >>> get_set_bits_count_using_modulo_operator(256) 1 >>> get_set_bits_count_using_modulo_operator(-1) Traceback (most recent call last): ... ValueError: the value of input must not be negative """ if number < 0: raise ValueError("the value of input must not be negative") result = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def benchmark() -> None: """ Benchmark code for comparing 2 functions, with different length int values. Brian Kernighan's algorithm is consistently faster than using modulo_operator. """ def do_benchmark(number: int) -> None: setup = "import __main__ as z" print(f"Benchmark when {number = }:") print(f"{get_set_bits_count_using_modulo_operator(number) = }") timing = timeit( f"z.get_set_bits_count_using_modulo_operator({number})", setup=setup ) print(f"timeit() runs in {timing} seconds") print(f"{get_set_bits_count_using_brian_kernighans_algorithm(number) = }") timing = timeit( f"z.get_set_bits_count_using_brian_kernighans_algorithm({number})", setup=setup, ) print(f"timeit() runs in {timing} seconds") for number in (25, 37, 58, 0): do_benchmark(number) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
Find excess3 code of integer base 10. Add 3 to all digits in a decimal number then convert to a binarycoded decimal. https:en.wikipedia.orgwikiExcess3 excess3code0 '0b0011' excess3code3 '0b0110' excess3code2 '0b0101' excess3code20 '0b01010011' excess3code120 '0b010001010011'
def excess_3_code(number: int) -> str: """ Find excess-3 code of integer base 10. Add 3 to all digits in a decimal number then convert to a binary-coded decimal. https://en.wikipedia.org/wiki/Excess-3 >>> excess_3_code(0) '0b0011' >>> excess_3_code(3) '0b0110' >>> excess_3_code(2) '0b0101' >>> excess_3_code(20) '0b01010011' >>> excess_3_code(120) '0b010001010011' """ num = "" for digit in str(max(0, number)): num += str(bin(int(digit) + 3))[2:].zfill(4) return "0b" + num if __name__ == "__main__": import doctest doctest.testmod()
Find the largest power of two that is less than or equal to a given integer. https:stackoverflow.comquestions1322510 findpreviouspoweroftwoi for i in range18 0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16 findpreviouspoweroftwo5 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer findpreviouspoweroftwo10.5 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer
def find_previous_power_of_two(number: int) -> int: """ Find the largest power of two that is less than or equal to a given integer. https://stackoverflow.com/questions/1322510 >>> [find_previous_power_of_two(i) for i in range(18)] [0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16] >>> find_previous_power_of_two(-5) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> find_previous_power_of_two(10.5) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer """ if not isinstance(number, int) or number < 0: raise ValueError("Input must be a non-negative integer") if number == 0: return 0 power = 1 while power <= number: power <<= 1 # Equivalent to multiplying by 2 return power >> 1 if number > 1 else 1 if __name__ == "__main__": import doctest doctest.testmod()
Takes in an integer n and returns a nbit gray code sequence An nbit gray code sequence is a sequence of 2n integers where: a Every integer is between 0,2n 1 inclusive b The sequence begins with 0 c An integer appears at most one times in the sequence dThe binary representation of every pair of integers differ by exactly one bit e The binary representation of first and last bit also differ by exactly one bit graycode2 0, 1, 3, 2 graycode1 0, 1 graycode3 0, 1, 3, 2, 6, 7, 5, 4 graycode1 Traceback most recent call last: ... ValueError: The given input must be positive graycode10.6 Traceback most recent call last: ... TypeError: unsupported operand types for : 'int' and 'float' bit count represents no. of bits in the gray code get the generated string sequence convert them to integers Will output the nbit grey sequence as a string of bits graycodesequencestring2 '00', '01', '11', '10' graycodesequencestring1 '0', '1' The approach is a recursive one Base case achieved when either n 0 or n1 1 n is equivalent to 2n recursive answer will generate answer for n1 bits append 0 to first half of the smaller sequence generated append 1 to second half ... start from the end of the list
def gray_code(bit_count: int) -> list: """ Takes in an integer n and returns a n-bit gray code sequence An n-bit gray code sequence is a sequence of 2^n integers where: a) Every integer is between [0,2^n -1] inclusive b) The sequence begins with 0 c) An integer appears at most one times in the sequence d)The binary representation of every pair of integers differ by exactly one bit e) The binary representation of first and last bit also differ by exactly one bit >>> gray_code(2) [0, 1, 3, 2] >>> gray_code(1) [0, 1] >>> gray_code(3) [0, 1, 3, 2, 6, 7, 5, 4] >>> gray_code(-1) Traceback (most recent call last): ... ValueError: The given input must be positive >>> gray_code(10.6) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for <<: 'int' and 'float' """ # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("The given input must be positive") # get the generated string sequence sequence = gray_code_sequence_string(bit_count) # # convert them to integers for i in range(len(sequence)): sequence[i] = int(sequence[i], 2) return sequence def gray_code_sequence_string(bit_count: int) -> list: """ Will output the n-bit grey sequence as a string of bits >>> gray_code_sequence_string(2) ['00', '01', '11', '10'] >>> gray_code_sequence_string(1) ['0', '1'] """ # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] seq_len = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits smaller_sequence = gray_code_sequence_string(bit_count - 1) sequence = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2): generated_no = "0" + smaller_sequence[i] sequence.append(generated_no) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2)): generated_no = "1" + smaller_sequence[i] sequence.append(generated_no) return sequence if __name__ == "__main__": import doctest doctest.testmod()
Returns position of the highest set bit of a number. Ref https:graphics.stanford.eduseanderbithacks.htmlIntegerLogObvious gethighestsetbitposition25 5 gethighestsetbitposition37 6 gethighestsetbitposition1 1 gethighestsetbitposition4 3 gethighestsetbitposition0 0 gethighestsetbitposition0.8 Traceback most recent call last: ... TypeError: Input value must be an 'int' type
def get_highest_set_bit_position(number: int) -> int: """ Returns position of the highest set bit of a number. Ref - https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious >>> get_highest_set_bit_position(25) 5 >>> get_highest_set_bit_position(37) 6 >>> get_highest_set_bit_position(1) 1 >>> get_highest_set_bit_position(4) 3 >>> get_highest_set_bit_position(0) 0 >>> get_highest_set_bit_position(0.8) Traceback (most recent call last): ... TypeError: Input value must be an 'int' type """ if not isinstance(number, int): raise TypeError("Input value must be an 'int' type") position = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
Reference: https:www.geeksforgeeks.orgpositionofrightmostsetbit Take in a positive integer 'number'. Returns the zerobased index of first set bit in that 'number' from right. Returns 1, If no set bit found. getindexofrightmostsetbit0 1 getindexofrightmostsetbit5 0 getindexofrightmostsetbit36 2 getindexofrightmostsetbit8 3 getindexofrightmostsetbit18 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer getindexofrightmostsetbit'test' Traceback most recent call last: ... ValueError: Input must be a nonnegative integer getindexofrightmostsetbit1.25 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer Finding the index of rightmost set bit has some very peculiar usecases, especially in finding missing orand repeating numbers in a list of positive integers.
# Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/ def get_index_of_rightmost_set_bit(number: int) -> int: """ Take in a positive integer 'number'. Returns the zero-based index of first set bit in that 'number' from right. Returns -1, If no set bit found. >>> get_index_of_rightmost_set_bit(0) -1 >>> get_index_of_rightmost_set_bit(5) 0 >>> get_index_of_rightmost_set_bit(36) 2 >>> get_index_of_rightmost_set_bit(8) 3 >>> get_index_of_rightmost_set_bit(-18) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> get_index_of_rightmost_set_bit('test') Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> get_index_of_rightmost_set_bit(1.25) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer """ if not isinstance(number, int) or number < 0: raise ValueError("Input must be a non-negative integer") intermediate = number & ~(number - 1) index = 0 while intermediate: intermediate >>= 1 index += 1 return index - 1 if __name__ == "__main__": """ Finding the index of rightmost set bit has some very peculiar use-cases, especially in finding missing or/and repeating numbers in a list of positive integers. """ import doctest doctest.testmod(verbose=True)
return true if the input integer is even Explanation: Lets take a look at the following decimal to binary conversions 2 10 14 1110 100 1100100 3 11 13 1101 101 1100101 from the above examples we can observe that for all the odd integers there is always 1 set bit at the end also, 1 in binary can be represented as 001, 00001, or 0000001 so for any odd integer n n1 is always equals 1 else the integer is even iseven1 False iseven4 True iseven9 False iseven15 False iseven40 True iseven100 True iseven101 False
def is_even(number: int) -> bool: """ return true if the input integer is even Explanation: Lets take a look at the following decimal to binary conversions 2 => 10 14 => 1110 100 => 1100100 3 => 11 13 => 1101 101 => 1100101 from the above examples we can observe that for all the odd integers there is always 1 set bit at the end also, 1 in binary can be represented as 001, 00001, or 0000001 so for any odd integer n => n&1 is always equals 1 else the integer is even >>> is_even(1) False >>> is_even(4) True >>> is_even(9) False >>> is_even(15) False >>> is_even(40) True >>> is_even(100) True >>> is_even(101) False """ return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()