Description
stringlengths
18
161k
Code
stringlengths
15
300k
type root treenode type k int rtype int 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): 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 type root node type p node type q node rtype node
def lowest_common_ancestor(root, p, q): 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 the tree is created for testing 9 6 12 3 8 10 15 7 18 num_empty 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) 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 type n int rtype int
def num_trees(n): 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 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): global pre_index if pre_index == -1: pre_index = 0 if(pre_index >= size or low > high): return None root = TreeNode(pre[pre_index]) pre_index += 1 if(low == high or pre_index >= size): return root i = low while i <= high: if(pre[pre_index] == post[i]): break i += 1 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): global pre_index root = construct_tree_util(pre, post, 0, size-1, size) return print_inorder(root) def print_inorder(root: TreeNode, result = None): 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 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 index in bit_tree is 1 more than the index in arr traverse ancestors of bit_tree index add current element of bit_tree to sum move index to parent node in getsum view 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 traverse all ancestors and add val add val to current node of bit_tree 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 bit_ree as 0 store the actual values in bit_ree using update
class Fenwick_Tree(object): def __init__(self, freq): self.arr = freq self.n = len(freq) def get_sum(self, bit_tree, i): s = 0 i = i+1 while i > 0: s += bit_tree[i] i -= i & (-i) return s def update_bit(self, bit_tree, i, v): i += 1 while i <= self.n: bit_tree[i] += v i += i & (-i) def construct(self): bit_tree = [0]*(self.n+1) 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 o n solution return 0 if unbalanced else depth 1 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
def is_balanced(root): return __is_balanced_recursive(root) def __is_balanced_recursive(root): return -1 != __get_depth(root) def __get_depth(root): 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)
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 popleft
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() 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 type root treenode rtype int
def longest_consecutive(root): 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 type root treenode type p treenode type q treenode rtype treenode
def lca(root, p, q): 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 type root treenode rtype int iterative
from tree import TreeNode def min_depth(self, root): 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 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 type root treenode type sum int rtype bool dfs with stack bfs with queue popleft
def has_path_sum(root, sum): 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) 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 def has_path_sum3(root, sum): if root is None: return False queue = [(root, sum-root.val)] while queue: node, val = queue.pop(0) 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 dfs with stack bfs with queue popleft
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) 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 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) 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 end prevents a newline character multiple lookups is expensive even amortized o 1 op wants indenting after digits newline and a space to match indenting forces a newline
from __future__ import print_function def tree_print(tree): for key in tree: print(key, end=' ') tree_element = tree[key] for subElem in tree_element: print(" -> ", subElem, end=' ') if type(subElem) != str: print("\n ") print()
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 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 node_u replaced node param node_v return none check is node_v 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): right_node = node.right if right_node is None: return else: node.right = right_node.left if right_node.left is not None: right_node.left.parent = node right_node.parent = node.parent 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): left_node = node.left if left_node is None: return else: node.left = left_node.right if left_node.right is not None: left_node.right.parent = node left_node.parent = node.parent 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): root = self.root insert_node_parent = None while root is not None: insert_node_parent = root if insert_node_parent.val < node.val: root = root.right else: root = root.left node.parent = insert_node_parent if insert_node_parent is None: self.root = node elif insert_node_parent.val > node.val: insert_node_parent.left = node else: insert_node_parent.right = node node.left = None node.right = None node.color = 1 self.fix_insert(node) def fix_insert(self, node): if node.parent is None: node.color = 0 self.root = node return 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: 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: node = node.parent self.left_rotate(node) 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: 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: node = node.parent self.right_rotate(node) 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): 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 if node_v: node_v.parent = node_u.parent def maximum(self, node): temp_node = node while temp_node.right is not None: temp_node = temp_node.right return temp_node def minimum(self, node): temp_node = node while temp_node.left: temp_node = temp_node.left return temp_node def delete(self, node): 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: 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 if node_color == 0: self.delete_fixup(temp_node) def delete_fixup(self, node): while node is not self.root and node.color == 0: if node is node.parent.left: node_brother = node.parent.right 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.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 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 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
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
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 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
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)
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 in order function recursive implementation
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def inorder(root): 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): 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 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 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 this is a class of node function to preorder recursive implementation
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def preorder(root): 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): 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 if dot if last character 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 letter == ".": if i == len(word) - 1: 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 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)]: 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 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 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 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
class Union: def __init__(self): self.parents = {} self.size = {} self.count = 0 def add(self, element): self.parents[element] = element self.size[element] = 1 self.count += 1 def root(self, 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): 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): 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 remove trailing remove leading
import os def join_with_slash(base, suffix): base = base.rstrip('/') 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 takt the origin path without the last part take the last element of list
import os def split(path): parts = [] split_part = path.rpartition('/') parts.append(split_part[0]) parts.append(split_part[2]) return parts
usrbinenv python3 coding utf8 algorithms documentation build configuration file 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 documentclass howto manual or own class options for manual page output one entry per manual page list of tuples source start file name description s manual section options for texinfo output grouping the document tree into texinfo files list of tuples source start file target name title dir menu entry description category usr bin env python3 coding utf 8 algorithms documentation build configuration file 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 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 add any paths that contain templates here relative to this directory the suffix es 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 alpha beta rc 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 html_static_path and html_extra_path 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 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 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 needs show_related true theme option to display 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 figure_align htbp grouping the document tree into latex files list of tuples source start file target name title documentclass howto manual or own class options for manual page output one entry per manual page list of tuples source start file name description s manual section options for texinfo output grouping the document tree into texinfo files list of tuples source start file target name title dir menu entry description category
from recommonmark.parser import CommonMarkParser 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'] templates_path = ['_templates'] source_parsers = { '.md': CommonMarkParser } source_suffix = ['.rst', '.md'] master_doc = 'index' project = 'algorithms' copyright = '2018, Algorithms Team & Contributors' author = 'Algorithms Team & Contributors' version = '0.1.0' release = '0.1.0' language = None exclude_patterns = [] pygments_style = 'sphinx' todo_include_todos = True html_theme = 'alabaster' html_static_path = ['_static'] html_sidebars = { '**': [ 'about.html', 'searchbox.html', 'navigation.html', 'relations.html', ] } htmlhelp_basename = 'algorithmsdoc' latex_elements = { } latex_documents = [ (master_doc, 'algorithms.tex', 'algorithms Documentation', 'Algorithms Team \\& Contributors', 'manual'), ] man_pages = [ (master_doc, 'algorithms', 'algorithms Documentation', [author], 1) ] texinfo_documents = [ (master_doc, 'algorithms', 'algorithms Documentation', author, 'algorithms', 'One line description of project.', 'Miscellaneous'), ]
123 6 123 123 232 8 232 232 123 6 1 2 3 1 2 3 232 8 2 3 2 2 3 2
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): s = "123" target = 6 self.assertEqual(add_operators(s, target), ["1+2+3", "1*2*3"]) 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 hit hot dot dog cog pick sick sink sank tank 5 live life 1 no matter what is the word_list 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): self.assertEqual(5, ladder_length('hit', 'cog', ["hot", "dot", "dog", "lot", "log"])) self.assertEqual(5, ladder_length('pick', 'tank', ['tock', 'tick', 'sank', 'sink', 'sick'])) self.assertEqual(1, ladder_length('live', 'life', ['hoho', 'luck'])) self.assertEqual(0, ladder_length('ate', 'ate', [])) 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 initialize seed 8 1000 109 1101101 63 111111 0 0 8 1000 109 1101101 63 111111 0 0 29 11101 and 15 01111 45 0000101101 and 987 1111011011 34 100010 34 100010 and 53 110101 1775 11011101111 5 101 71 1000111 0 0 bin 0 00000000000000000000000000000000 bin 2 32 1 11111111111111111111111111111111 nums contains pairs of random integers nums contains triplets of random integers 22 10110 22 10110 after set bit at 3th position 30 11110 22 10110 after clear bit at 2nd position 20 10010 22 10110 after update bit at 3th position with value 1 30 11110 22 10110 after update bit at 2nd position with value 0 20 10010 22 10110 41 101001 10 1010 5 0101 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 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 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 22 10110 6 110 8 1000 145 10010001
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): 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): self.assertEqual(1, count_ones_recur(8)) self.assertEqual(5, count_ones_recur(109)) self.assertEqual(6, count_ones_recur(63)) self.assertEqual(0, count_ones_recur(0)) def test_count_ones_iter(self): self.assertEqual(1, count_ones_iter(8)) self.assertEqual(5, count_ones_iter(109)) self.assertEqual(6, count_ones_iter(63)) self.assertEqual(0, count_ones_iter(0)) def test_count_flips_to_convert(self): self.assertEqual(2, count_flips_to_convert(29, 15)) self.assertEqual(8, count_flips_to_convert(45, 987)) self.assertEqual(0, count_flips_to_convert(34, 34)) 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): self.assertEqual(8, flip_bit_longest_seq(1775)) self.assertEqual(3, flip_bit_longest_seq(5)) self.assertEqual(4, flip_bit_longest_seq(71)) 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)) self.assertEqual(0, reverse_bits(0)) 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.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.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): self.assertEqual(1, get_bit(22, 2)) self.assertEqual(0, get_bit(22, 3)) def test_set_bit(self): self.assertEqual(30, set_bit(22, 3)) def test_clear_bit(self): self.assertEqual(18, clear_bit(22, 2)) def test_update_bit(self): self.assertEqual(30, update_bit(22, 3, 1)) 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): self.assertEqual(41, swap_pair(22)) 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): 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): 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): 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): self.assertEqual(2, binary_gap(22)) self.assertEqual(1, binary_gap(6)) self.assertEqual(0, binary_gap(8)) 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 summary test for the file hosoya_triangle 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): 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): n1 = 4 k1 = 1 self.assertEqual(find_k_factor(n1, k1), 1) n2 = 7 k2 = 1 self.assertEqual(find_k_factor(n2, k2), 70302) n3 = 10 k3 = 2 self.assertEqual(find_k_factor(n3, k3), 74357) n4 = 8 k4 = 2 self.assertEqual(find_k_factor(n4, k4), 53) n5 = 9 k5 = 1 self.assertEqual(find_k_factor(n5, k5), 71284044) class TestPlantingTrees(unittest.TestCase): def test_simple(self): trees = [0, 1, 10, 10] L = 10 W = 1 res = planting_trees(trees, L, W) self.assertEqual(res, 2.414213562373095) def test_simple2(self): trees = [0, 3, 5, 5, 6, 9] L = 10 W = 1 res = planting_trees(trees, L, W) 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): 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 test for the file tarjan py arguments unittest type description graph from https en wikipedia org wiki file scc png graph from https en wikipedia org wiki tarjan 27s_strongly_connected_components_algorithm media file tarjan 27s_algorithm_animation gif test for the file maximum_flow py arguments unittest type description test for the file def maximum_flow_bfs py arguments unittest type description test for the file def maximum_flow_dfs 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 2 0 1 5 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): def test_tarjan_example_1(self): 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): 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): 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): 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): 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): def test_count_connected_components(self): expected_result = 3 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): 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): 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 test suite for the binary_heap data structures before insert 2 0 4 50 7 55 90 87 after insert 0 2 50 4 55 90 87 7 before remove_min 0 4 50 7 55 90 87 after remove_min 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): 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): 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() 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]] 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 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): 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): segment_tree = SegmentTree(arr, fnc) self.__test_segments_helper(segment_tree, fnc, arr) def __test_all_segments_with_updates(self, arr, fnc, upd): 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 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 1 2 3 4 5 null k 2 expect output 4 5 1 2 3 null create linked list a b c d e c create linked list 1 2 3 4 input head1 1 2 4 head2 1 3 4 output 1 1 2 3 4 4 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 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): 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) 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) self.assertFalse(is_sorted(head)) def test_remove_range(self): 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([0, 4], convert(remove_range(head, 1, 3))) 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([2, 3, 4], convert(remove_range(head, 0, 1))) 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) self.assertEqual([2, 1, 4, 3], convert(swap_pairs(head))) def test_rotate_right(self): 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) self.assertEqual([4, 5, 1, 2, 3], convert(rotate_right(head, 2))) def test_is_cyclic(self): 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)) 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): 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))) 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 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): 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 test for the file power py arguments unittest type description test for the file base_conversion py arguments unittest type description test for the file decimal_to_binary_ip py arguments unittest type description summary test for the file euler_totient py arguments unittest type description summary test for the file extended_gcd py arguments unittest type description summary test for the file gcd py arguments unittest type description summary test for the file generate_strobogrammatic py arguments unittest type description summary test for the file is_strobogrammatic py arguments unittest type description summary test for the file modular_exponential py arguments unittest type description checks if x x_inv 1 mod m summary test for the file modular_exponential py arguments unittest type description summary test for the file next_perfect_square py arguments unittest type description summary test for the file primes_sieve_of_eratosthenes py arguments unittest type description summary test for the file prime_test 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 rabin_miller py arguments unittest type description summary test for the file rsa py arguments unittest type description 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 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 cosine_similarity py arguments unittest type description summary test for the file find_primitive_root_simple py arguments unittest type description summary test for the file find_order_simple py arguments unittest type description summary test for the file krishnamurthy_number py arguments unittest type description summary test for the file find_order_simple py arguments unittest type description summary test for the file diffie_hellman_key_exchange py arguments unittest type description summary test for the file num_digits py arguments unittest type description summary test for the file num_perfect_squares 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 abs complex 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): 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): 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): 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): 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): 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): 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): 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): 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): def test_modular_inverse(self): 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): 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): 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): def test_primes(self): self.assertListEqual([2, 3, 5, 7], get_primes(7)) self.assertRaises(ValueError, get_primes, -42) class TestPrimeTest(unittest.TestCase): def test_prime_test(self): counter = 0 for i in range(2, 101): if prime_check(i): counter += 1 self.assertEqual(25, counter) class TestPythagoras(unittest.TestCase): def test_pythagoras(self): self.assertEqual("Hypotenuse = 3.605551275463989", pythagoras(3, 2, "?")) class TestRabinMiller(unittest.TestCase): 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): def test_encrypt_decrypt(self): self.assertEqual(7, decrypt(encrypt(7, 23, 143), 47, 143)) class TestCombination(unittest.TestCase): 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): 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): 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): 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): 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): 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): 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): 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): 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): 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): 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): num = [3, 7, 10] rem = [2, 3, 3] self.assertEqual(chinese_remainder_theorem. solve_chinese_remainder(num, rem), 143) def test_k_five(self): 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): 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): 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] 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 summary test for the file copy_transform py arguments unittest type description summary test for the file crout_matrix_decomposition py arguments unittest type description summary test for the file cholesky_matrix_decomposition py arguments unittest type description example taken from https ece uwaterloo ca dwharder numericalanalysis 04linearalgebra cholesky summary test for the file matrix_inversion py arguments unittest type description summary test for the file matrix_exponentiation py arguments unittest type description summary test for the file multiply py arguments unittest type description summary test for the file rotate_image py arguments unittest type description summary test for the file sparse_dot_vector py arguments unittest type description summary test for the file spiral_traversal py arguments unittest type description summary test for the file sudoku_validator py arguments unittest type description summary test for the file sum_sub_squares 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): 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): 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): 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]])) 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): 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): 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): def test_multiply(self): self.assertEqual(multiply.multiply( [[1, 2, 3], [2, 1, 1]], [[1], [2], [3]]), [[14], [7]]) class TestRotateImage(unittest.TestCase): 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): 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): 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): 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): 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 train set for the and function train set for light or dark colors and function dark light color test
from algorithms.ml.nearest_neighbor import ( distance, nearest_neighbor ) import unittest class TestML(unittest.TestCase): def setUp(self): self.trainSetAND = {(0, 0): 0, (0, 1): 0, (1, 0): 0, (1, 1): 1} 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): self.assertEqual(nearest_neighbor((1, 1), self.trainSetAND), 1) self.assertEqual(nearest_neighbor((0, 1), self.trainSetAND), 0) 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 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): 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) self.assertEqual(self.m13 + self.m2, self.m1) self.assertEqual(self.m1 + self.m1, self.m1) self.assertEqual(self.m7 + self.m7, Monomial({1: 2, 7: 2}, -2 * math.pi)) self.assertEqual(self.m8, self.m1) self.assertRaises(ValueError, lambda x, y: x + y, self.m2, self.m9) self.assertRaises(TypeError, lambda x, y: x + y, self.m9, self.m2) self.assertEqual(self.m1 + self.m9, Monomial({}, 2)) self.assertEqual(self.m1 + self.m12, Monomial({}, 0)) return def test_monomial_subtraction(self): 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) self.assertEqual(self.m2 - self.m2, self.m1) self.assertEqual(self.m2 - self.m2, Monomial({}, 0)) self.assertEqual(self.m1 - self.m1, self.m1) self.assertEqual(self.m2 - self.m15, Monomial({1: 1}, -1)) self.assertEqual(self.m16 - self.m7, Monomial({1: 2, 7: 2}, 2 * math.pi)) self.assertRaises(ValueError, lambda x, y: x - y, self.m2, self.m9) self.assertRaises(TypeError, lambda x, y: x - y, self.m9, self.m2) self.assertEqual(self.m1 - self.m9, Monomial({}, -2)) self.assertEqual(self.m1 - self.m12, Monomial({}, 0)) return def test_monomial_multiplication(self): self.assertEqual(self.m2 * self.m13, Monomial({1: 2}, -4)) self.assertEqual(self.m2 * self.m17, Monomial({}, 2)) self.assertEqual(self.m8 * self.m5, self.m1) self.assertEqual(self.m1 * self.m2, self.m1) self.assertEqual(self.m7 * self.m3, Monomial({1: 4, 2: -1, 7: 2}, -1.5*math.pi)) return def test_monomial_inverse(self): 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)) self.assertEqual(self.m7.inverse(), Monomial({1: -2, 7: -2}, -1 / math.pi)) self.assertEqual(self.m5.inverse(), Monomial({2: -1}, Fraction(3, 2))) self.assertEqual(self.m5.inverse(), Monomial({2: -1}, 1.5)) self.assertTrue(self.m6.inverse(), Monomial({}, Fraction(-100, 227))) self.assertEqual(self.m6.inverse(), Monomial({}, -1/2.27)) return def test_monomial_division(self): 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) 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): self.assertAlmostEqual(self.m7.substitute(2), -16 * math.pi, delta=1e-9) self.assertAlmostEqual(self.m7.substitute(1.5), (1.5 ** 4) * -math.pi, delta=1e-9) self.assertAlmostEqual(self.m7.substitute(Fraction(-1, 2)), (Fraction(-1, 2) ** 4)*-math.pi, delta=1e-9) self.assertAlmostEqual(self.m7.substitute({1: 3, 7: 0}), (3 ** 2) * (0 ** 2) * -math.pi, delta=1e-9) self.assertAlmostEqual(self.m7.substitute({1: 3, 7: 0, 2: 2}), (3 ** 2) * (0 ** 2) * -math.pi, delta=1e-9) 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}) self.assertEqual(self.m8.substitute(2), 0) self.assertEqual(self.m8.substitute({1231: 2, 1: 2}), 0) return def test_monomial_all_variables(self): self.assertEqual(self.m5.all_variables(), {2}) self.assertEqual(self.m6.all_variables(), set()) self.assertEqual(self.m8.all_variables(), set()) return def test_monomial_clone(self): self.assertEqual(self.m3, self.m3.clone()) 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 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): self.assertEqual(self.p0 + self.p1, self.p0) self.assertEqual(self.p0 + self.p1, self.p1) self.assertEqual(self.p3 + self.p7, self.p0) self.assertEqual(self.p3 + self.p7, self.p1) 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), ])) 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): 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): self.assertEqual(self.p0.variables(), set()) self.assertEqual(self.p1.variables(), set()) self.assertEqual(self.p4.variables(), {1, 2, 3}) self.assertEqual(self.p5.variables(), {1, 3}) return def test_polynomial_subs(self): self.assertEqual(self.p1.subs(2), 0) self.assertEqual(self.p0.subs(-101231), 0) 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, {}) self.assertAlmostEqual(self.p4.subs({1: 1, 2: 1, 3: 1}), (1 + math.pi + Fraction(2, 3)), delta=1e-9) 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): 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) self.assertEqual(self.p4.clone(), self.p4) 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 test suite for the queue data structures test __iter__ test __len__ test is_empty test peek test dequeue test __iter__ test __len__ test is_empty 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): def test_ArrayQueue(self): queue = ArrayQueue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) it = iter(queue) self.assertEqual(1, next(it)) self.assertEqual(2, next(it)) self.assertEqual(3, next(it)) self.assertRaises(StopIteration, next, it) self.assertEqual(3, len(queue)) self.assertFalse(queue.is_empty()) self.assertEqual(1, queue.peek()) 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) it = iter(queue) self.assertEqual(1, next(it)) self.assertEqual(2, next(it)) self.assertEqual(3, next(it)) self.assertRaises(StopIteration, next, it) self.assertEqual(3, len(queue)) self.assertFalse(queue.is_empty()) self.assertEqual(1, queue.peek()) 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): 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 test binary_search_recur test two_sum test two_sum1 test two_sum2 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)) 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] self.assertEqual([1, 2], two_sum(array, 9)) self.assertEqual([2, 4], two_sum(array, 22)) self.assertEqual([1, 2], two_sum1(array, 9)) self.assertEqual([2, 4], two_sum1(array, 22)) 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)) 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 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 print res
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): 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) 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 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 is_empty test peek test pop test __iter__ test __len__ test __str__ test is_empty 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): 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): self.assertEqual([2, 8, 3, 7, 3], remove_min([2, 8, 3, -6, 7, 3])) self.assertEqual([4, 8, 7], remove_min([4, 8, 3, 7, 3])) def test_stutter(self): 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): 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])) 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) it = iter(stack) self.assertEqual(3, next(it)) self.assertEqual(2, next(it)) self.assertEqual(1, next(it)) self.assertRaises(StopIteration, next, it) self.assertEqual(3, len(stack)) self.assertEqual(str(stack), "Top-> 3 2 1") self.assertFalse(stack.is_empty()) self.assertEqual(3, stack.peek()) 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) it = iter(stack) self.assertEqual(3, next(it)) self.assertEqual(2, next(it)) self.assertEqual(1, next(it)) self.assertRaises(StopIteration, next, it) self.assertEqual(3, len(stack)) self.assertEqual(str(stack), "Top-> 3 2 1") self.assertFalse(stack.is_empty()) self.assertEqual(3, stack.peek()) 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 two values remaining no values remaining 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, '+')])) self.assertEqual(None, one_sparse([(2, '+'), (2, '+'), (2, '+'), (2, '+'), (2, '-'), (2, '-'), (2, '-'), (2, '-')])) self.assertEqual(None, one_sparse([(2, '+'), (2, '+'), (4, '+'), (4, '+')]))
test 1 test 2 test 3 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): 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]) 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]) 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 test full path relative test full path with expanding user file_name 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" expect_path = "{}/{}".format(os.getcwd(), file_name) self.assertEqual(expect_path, full_path(file_name)) expect_path = "{}/{}".format(os.path.expanduser('~'), file_name) self.assertEqual(expect_path, full_path("~/{}".format(file_name))) def test_split(self): 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]) 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 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 noqa b008 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 noqa b008 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 noqa b008 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 noqa b008 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 noqa b008 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 noqa b008 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 noqa b008 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
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def make_lowpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: 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) ) -> IIRFilter: 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) ) -> IIRFilter: 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) ) -> IIRFilter: 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), ) -> IIRFilter: 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), ) -> IIRFilter: 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), ) -> IIRFilter: 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 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 a_ 0 a_ k b_ 0 b_ k x n 1 x n k y n 1 y n k 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 calculate y n filt iirfilter 2 filt process 0 0 0 start at index 1 and do index 0 at the end
from __future__ import annotations class IIRFilter: r def __init__(self, order: int) -> None: self.order = order self.a_coeffs = [1.0] + [0.0] * order self.b_coeffs = [1.0] + [0.0] * order self.input_history = [0.0] * self.order self.output_history = [0.0] * self.order def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None: 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: result = 0.0 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 calculate y n issubclass filtertype protocol true get bounds for printing fft results import numpy array numpy linspace 20 0 20 0 1000 get_bounds array 1000 20 20 show frequency response of a filter from audio_filters iir_filter import iirfilter filt iirfilter 4 show_frequency_response filt 48000 zero padding frequencies on log scale from 24 to nyquist frequency display within reasonable bounds show phase response of a filter from audio_filters iir_filter import iirfilter filt iirfilter 4 show_phase_response filt 48000 zero padding 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: return 0.0 def get_bounds( fft_results: np.ndarray, samplerate: int ) -> tuple[int | float, int | float]: 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: size = 512 inputs = [1] + [0] * (size - 1) outputs = [filter_type.process(item) for item in inputs] filler = [0] * (samplerate - size) outputs += filler fft_out = np.abs(np.fft.fft(outputs)) fft_db = 20 * np.log10(fft_out) plt.xlim(24, samplerate / 2 - 1) plt.xlabel("Frequency (Hz)") plt.xscale("log") 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: size = 512 inputs = [1] + [0] * (size - 1) outputs = [filter_type.process(item) for item in inputs] filler = [0] * (samplerate - size) outputs += filler fft_out = np.angle(np.fft.fft(outputs)) 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 combination_lists n 4 k 2 1 2 1 3 1 4 2 3 2 4 3 4 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
from __future__ import annotations from itertools import combinations def combination_lists(n: int, k: int) -> list[list[int]]: return [list(x) for x in combinations(range(1, n + 1), k)] def generate_all_combinations(n: int, k: int) -> list[list[int]]: 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 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 remove the comment to take an input from the user print enter the elements sequence list map int 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: 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 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 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: 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 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 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 recursive step color current vertex validate coloring backtrack 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
def valid_coloring( neighbours: list[int], colored_vertices: list[int], color: int ) -> bool: 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: if index == len(graph): return True for i in range(max_colors): if valid_coloring(graph[index], colored_vertices, i): colored_vertices[index] = i if util_color(graph, max_colors, colored_vertices, index + 1): return True colored_vertices[index] = -1 return False def color(graph: list[list[int]], max_colors: int) -> list[int]: 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 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 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 type list int type list int
def backtrack( candidates: list, path: list, answer: list, target: int, previous_index: int ) -> None: 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: path = [] answer = [] 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 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 place a word at the given position puzzle place_word puzzle word 0 0 true puzzle w o r d remove a word from the given position puzzle w o r d remove_word puzzle word 0 0 true puzzle 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
def is_valid( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> bool: 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: 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: 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: 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:")
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 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 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 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
def backtrack( partial: str, open_count: int, close_count: int, n: int, result: list[str] ) -> None: if len(partial) == 2 * n: result.append(partial) return if open_count < n: backtrack(partial + "(", open_count + 1, close_count, n, result) if close_count < open_count: backtrack(partial + ")", open_count, close_count + 1, n, result) def generate_parenthesis(n: int) -> list[str]: 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 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 2 validate that next vertex is not already in path 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 return whether path exists between current and starting vertices recursive step insert current vertex into path as next transition validate created path backtrack 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 initialize start and end of path with starting index evaluate and if we find answer return path either return empty array
def valid_connection( graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int] ) -> bool: if graph[path[curr_ind - 1]][next_ver] == 0: return False 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: if curr_ind == len(graph): return graph[path[curr_ind - 1]][path[0]] == 1 for next_ver in range(len(graph)): if valid_connection(graph, next_ver, curr_ind, path): path[curr_ind] = next_ver if util_hamilton_cycle(graph, path, curr_ind + 1): return True path[curr_ind] = -1 return False def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]: r path = [-1] * (len(graph) + 1) path[0] = path[-1] = start_index 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 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 check if the board matrix has been completely filled with non zero values is_complete 1 true is_complete 1 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 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
from __future__ import annotations def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]: 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: 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: 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]]: 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 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 backtrack 0 0 true backtrack 0 1 true backtrack 0 4 false
def match_word_pattern(pattern: str, input_string: str) -> bool: def backtrack(pattern_index: int, str_index: int) -> bool: 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 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 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: if depth < 0: raise ValueError("Depth cannot be less than 0") if len(scores) == 0: raise ValueError("Scores cannot be empty") if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1, node_index * 2, False, scores, height), minimax(depth + 1, node_index * 2 + 1, False, scores, height), ) return min( minimax(depth + 1, node_index * 2, True, scores, height), minimax(depth + 1, node_index * 2 + 1, True, scores, height), ) def main() -> None: scores = [90, 23, 6, 33, 21, 65, 123, 34423] height = math.log(len(scores), 2) 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 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 size of the board 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 queen is present empty cell number of queens e g n 8 for an 8x8 board
from __future__ import annotations solution = [] def is_safe(board: list[list[int]], row: int, column: int) -> bool: n = len(board) 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: if row >= len(board): solution.append(board) printboard(board) print() return True for i in range(len(board)): 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: for i in range(len(board)): for j in range(len(board)): if board[i][j] == 1: print("Q", end=" ") else: print(".", end=" ") print() 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))
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 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 the sum of the powers is equal to needed_sum then we have a solution if the sum of the powers is less than needed_sum then continue adding powers if the power of i is less than needed_sum then try with the next power 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 return the solutions_count
def backtrack( needed_sum: int, power: int, current_number: int, current_sum: int, solutions_count: int, ) -> tuple[int, int]: if current_sum == needed_sum: solutions_count += 1 return current_sum, solutions_count i_to_n = current_number**power if current_sum + i_to_n <= needed_sum: 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: 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: 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] 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 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 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 lower bounds check upper bounds 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]]: size = len(maze) 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") 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: size = len(maze) 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) upper_flag = (i < size) and (j < size) if lower_flag and upper_flag: block_flag = (solutions[i][j]) and (not maze[i][j]) if block_flag: solutions[i][j] = 0 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 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 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 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]] 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], ] 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: 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: 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: if location := find_empty_location(grid): row, column = location else: 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: for row in grid: for cell in row: print(cell, end=" ") print() if __name__ == "__main__": 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 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 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
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: 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], ) nums = [3, 34, 4, 12, 5, 2] max_sum = 9 result = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
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 returns the hash key of matrix indexes get_point_key 10 20 1 0 200 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 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 validate word
def get_point_key(len_board: int, len_board_column: int, row: int, column: int) -> int: 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: 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: 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) 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 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 remove the leading 0b remove the leading 0b
def binary_and(a: int, b: int) -> str: if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] b_binary = str(bin(b))[2:] 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 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
def binary_coded_decimal(number: int) -> str: 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 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
def binary_count_setbits(a: int) -> 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 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
from math import log2 def binary_count_trailing_zeros(a: int) -> 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 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 remove the leading 0b
def binary_or(a: int, b: int) -> str: if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] 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 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 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 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 get binary representation of positive number get binary 2 s complement representation of negative number find 2 s complement of number
def logical_left_shift(number: int, shift_amount: int) -> str: 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: 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: if number >= 0: binary_number = "0" + str(bin(number)).strip("-")[2:] else: binary_number_length = len(bin(number)[3:]) 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 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
def twos_complement(number: int) -> str: 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 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 remove the leading 0b remove the leading 0b
def binary_xor(a: int, b: int) -> str: if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] b_binary = str(bin(b))[2:] 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 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
def bitwise_addition_recursive(number: int, other_number: int) -> int: 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 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 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: if not isinstance(number, int) or number < 0: raise ValueError("Input must be a non-negative integer") count = 0 while number: 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 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 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 benchmark code for comparing 2 functions with different length int values brian kernighan s algorithm is consistently faster than using modulo_operator
from timeit import timeit def get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int: 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: 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: 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 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
def excess_3_code(number: int) -> str: 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 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 equivalent to multiplying by 2
def find_previous_power_of_two(number: int) -> int: 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 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 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 get the generated string sequence convert them to integers 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 defines the length of the sequence 1 n is equivalent to 2 n recursive answer will generate answer for n 1 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: if bit_count < 0: raise ValueError("The given input must be positive") sequence = gray_code_sequence_string(bit_count) for i in range(len(sequence)): sequence[i] = int(sequence[i], 2) return sequence def gray_code_sequence_string(bit_count: int) -> list: if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] seq_len = 1 << bit_count smaller_sequence = gray_code_sequence_string(bit_count - 1) sequence = [] for i in range(seq_len // 2): generated_no = "0" + smaller_sequence[i] sequence.append(generated_no) 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 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
def get_highest_set_bit_position(number: int) -> int: 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 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 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
def get_index_of_rightmost_set_bit(number: int) -> int: 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__": 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 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
def is_even(number: int) -> bool: return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
alexander pantyukhin date november 1 2022 task given a positive int number return true if this number is power of 2 or false otherwise implementation notes use bit manipulation for example if the number is the power of two it s bits representation n 0 100 00 n 1 0 011 11 n n 1 no intersections 0 return true if this number is power of 2 or false otherwise ispoweroftwo0 true ispoweroftwo1 true ispoweroftwo2 true ispoweroftwo4 true ispoweroftwo6 false ispoweroftwo8 true ispoweroftwo17 false ispoweroftwo1 traceback most recent call last valueerror number must not be negative ispoweroftwo1 2 traceback most recent call last typeerror unsupported operand types for float and float test all powers of 2 from 0 to 10 000 allispoweroftwoint2 i for i in range10000 true return true if this number is power of 2 or false otherwise is_power_of_two 0 true is_power_of_two 1 true is_power_of_two 2 true is_power_of_two 4 true is_power_of_two 6 false is_power_of_two 8 true is_power_of_two 17 false is_power_of_two 1 traceback most recent call last valueerror number must not be negative is_power_of_two 1 2 traceback most recent call last typeerror unsupported operand type s for float and float test all powers of 2 from 0 to 10 000 all is_power_of_two int 2 i for i in range 10000 true
def is_power_of_two(number: int) -> bool: if number < 0: raise ValueError("number must not be negative") return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
naman sharma date october 2 2023 task to find the largest power of 2 less than or equal to a given number implementation notes use bit manipulation we start from 1 left shift the set bit to check if res1number each left bit shift represents a pow of 2 for example number 15 res 1 0b1 2 0b10 4 0b100 8 0b1000 16 0b10000 exit return the largest power of two less than or equal to a number largestpowoftwolenum0 0 largestpowoftwolenum1 1 largestpowoftwolenum1 0 largestpowoftwolenum3 2 largestpowoftwolenum15 8 largestpowoftwolenum99 64 largestpowoftwolenum178 128 largestpowoftwolenum999999 524288 largestpowoftwolenum99 9 traceback most recent call last typeerror input value must be a int type return the largest power of two less than or equal to a number largest_pow_of_two_le_num 0 0 largest_pow_of_two_le_num 1 1 largest_pow_of_two_le_num 1 0 largest_pow_of_two_le_num 3 2 largest_pow_of_two_le_num 15 8 largest_pow_of_two_le_num 99 64 largest_pow_of_two_le_num 178 128 largest_pow_of_two_le_num 999999 524288 largest_pow_of_two_le_num 99 9 traceback most recent call last typeerror input value must be a int type
def largest_pow_of_two_le_num(number: int) -> int: if isinstance(number, float): raise TypeError("Input value must be a 'int' type") if number <= 0: return 0 res = 1 while (res << 1) <= number: res <<= 1 return res if __name__ == "__main__": import doctest doctest.testmod()
finds the missing number in a list of consecutive integers args nums a list of integers returns the missing number example findmissingnumber0 1 3 4 2 findmissingnumber4 3 1 0 2 findmissingnumber4 3 1 0 2 findmissingnumber2 2 1 3 0 1 findmissingnumber1 3 4 5 6 2 findmissingnumber6 5 4 2 1 3 findmissingnumber6 1 5 3 4 2 finds the missing number in a list of consecutive integers args nums a list of integers returns the missing number example find_missing_number 0 1 3 4 2 find_missing_number 4 3 1 0 2 find_missing_number 4 3 1 0 2 find_missing_number 2 2 1 3 0 1 find_missing_number 1 3 4 5 6 2 find_missing_number 6 5 4 2 1 3 find_missing_number 6 1 5 3 4 2
def find_missing_number(nums: list[int]) -> int: low = min(nums) high = max(nums) missing_number = high for i in range(low, high): missing_number ^= i ^ nums[i - low] return missing_number if __name__ == "__main__": import doctest doctest.testmod()
alexander pantyukhin date november 30 2022 task given two int numbers return true these numbers have opposite signs or false otherwise implementation notes use bit manipulation use xor for two numbers return true if numbers have opposite signs false otherwise differentsigns1 1 true differentsigns1 1 false differentsigns1000000000000000000000000000 1000000000000000000000000000 true differentsigns1000000000000000000000000000 1000000000000000000000000000 true differentsigns50 278 false differentsigns0 2 false differentsigns2 0 false return true if numbers have opposite signs false otherwise different_signs 1 1 true different_signs 1 1 false different_signs 1000000000000000000000000000 1000000000000000000000000000 true different_signs 1000000000000000000000000000 1000000000000000000000000000 true different_signs 50 278 false different_signs 0 2 false different_signs 2 0 false
def different_signs(num1: int, num2: int) -> bool: return num1 ^ num2 < 0 if __name__ == "__main__": import doctest doctest.testmod()
task given a positive int number return true if this number is power of 4 or false otherwise implementation notes use bit manipulation for example if the number is the power of 2 it s bits representation n 0 100 00 n 1 0 011 11 n n 1 no intersections 0 if the number is a power of 4 then it should be a power of 2 and the set bit should be at an odd position return true if this number is power of 4 or false otherwise powerof40 traceback most recent call last valueerror number must be positive powerof41 true powerof42 false powerof44 true powerof46 false powerof48 false powerof417 false powerof464 true powerof41 traceback most recent call last valueerror number must be positive powerof41 2 traceback most recent call last typeerror number must be an integer return true if this number is power of 4 or false otherwise power_of_4 0 traceback most recent call last valueerror number must be positive power_of_4 1 true power_of_4 2 false power_of_4 4 true power_of_4 6 false power_of_4 8 false power_of_4 17 false power_of_4 64 true power_of_4 1 traceback most recent call last valueerror number must be positive power_of_4 1 2 traceback most recent call last typeerror number must be an integer
def power_of_4(number: int) -> bool: if not isinstance(number, int): raise TypeError("number must be an integer") if number <= 0: raise ValueError("number must be positive") if number & (number - 1) == 0: c = 0 while number: c += 1 number >>= 1 return c % 2 == 1 else: return False if __name__ == "__main__": import doctest doctest.testmod()
return the bit string of an integer getreversebitstring9 10010000000000000000000000000000 getreversebitstring43 11010100000000000000000000000000 getreversebitstring2873 10011100110100000000000000000000 getreversebitstringthis is not a number traceback most recent call last typeerror operation can not be conducted on a object of type str take in an 32 bit integer reverse its bits return a string of reverse bits result of a reversebit and operation on the integer provided reversebit25 00000000000000000000000000011001 reversebit37 00000000000000000000000000100101 reversebit21 00000000000000000000000000010101 reversebit58 00000000000000000000000000111010 reversebit0 00000000000000000000000000000000 reversebit256 00000000000000000000000100000000 reversebit1 traceback most recent call last valueerror the value of input must be positive reversebit1 1 traceback most recent call last typeerror input value must be a int type reversebit0 traceback most recent call last typeerror not supported between instances of str and int iterator over 1 to 32 since we are dealing with 32 bit integer left shift the bits by unity get the end bit right shift the bits by unity add that bit to our ans return the bit string of an integer get_reverse_bit_string 9 10010000000000000000000000000000 get_reverse_bit_string 43 11010100000000000000000000000000 get_reverse_bit_string 2873 10011100110100000000000000000000 get_reverse_bit_string this is not a number traceback most recent call last typeerror operation can not be conducted on a object of type str take in an 32 bit integer reverse its bits return a string of reverse bits result of a reverse_bit and operation on the integer provided reverse_bit 25 00000000000000000000000000011001 reverse_bit 37 00000000000000000000000000100101 reverse_bit 21 00000000000000000000000000010101 reverse_bit 58 00000000000000000000000000111010 reverse_bit 0 00000000000000000000000000000000 reverse_bit 256 00000000000000000000000100000000 reverse_bit 1 traceback most recent call last valueerror the value of input must be positive reverse_bit 1 1 traceback most recent call last typeerror input value must be a int type reverse_bit 0 traceback most recent call last typeerror not supported between instances of str and int iterator over 1 to 32 since we are dealing with 32 bit integer left shift the bits by unity get the end bit right shift the bits by unity add that bit to our ans
def get_reverse_bit_string(number: int) -> str: if not isinstance(number, int): msg = ( "operation can not be conducted on a object of type " f"{type(number).__name__}" ) raise TypeError(msg) bit_string = "" for _ in range(32): bit_string += str(number % 2) number = number >> 1 return bit_string def reverse_bit(number: int) -> str: if number < 0: raise ValueError("the value of input must be positive") elif isinstance(number, float): raise TypeError("Input value must be a 'int' type") elif isinstance(number, str): raise TypeError("'<' not supported between instances of 'str' and 'int'") result = 0 for _ in range(1, 33): result = result << 1 end_bit = number % 2 number = number >> 1 result = result | end_bit return get_reverse_bit_string(result) if __name__ == "__main__": import doctest doctest.testmod()
usrbinenv python3 provide the functionality to manipulate a single bit def setbitnumber int position int int return number 1 position def clearbitnumber int position int int return number 1 position def flipbitnumber int position int int return number 1 position def isbitsetnumber int position int bool return number position 1 1 def getbitnumber int position int int return intnumber 1 position 0 if name main import doctest doctest testmod usr bin env python3 provide the functionality to manipulate a single bit set the bit at position to 1 details perform bitwise or for given number and x where x is a number with all the bits zeroes and bit on given position one set_bit 0b1101 1 0b1111 15 set_bit 0b0 5 0b100000 32 set_bit 0b1111 1 0b1111 15 set the bit at position to 0 details perform bitwise and for given number and x where x is a number with all the bits ones and bit on given position zero clear_bit 0b10010 1 0b10000 16 clear_bit 0b0 5 0b0 0 flip the bit at position details perform bitwise xor for given number and x where x is a number with all the bits zeroes and bit on given position one flip_bit 0b101 1 0b111 7 flip_bit 0b101 0 0b100 4 is the bit at position set details shift the bit at position to be the first smallest bit then check if the first bit is set by anding the shifted number with 1 is_bit_set 0b1010 0 false is_bit_set 0b1010 1 true is_bit_set 0b1010 2 false is_bit_set 0b1010 3 true is_bit_set 0b0 17 false get the bit at the given position details perform bitwise and for the given number and x where x is a number with all the bits zeroes and bit on given position one if the result is not equal to 0 then the bit on the given position is 1 else 0 get_bit 0b1010 0 0 get_bit 0b1010 1 1 get_bit 0b1010 2 0 get_bit 0b1010 3 1
def set_bit(number: int, position: int) -> int: return number | (1 << position) def clear_bit(number: int, position: int) -> int: return number & ~(1 << position) def flip_bit(number: int, position: int) -> int: return number ^ (1 << position) def is_bit_set(number: int, position: int) -> bool: return ((number >> position) & 1) == 1 def get_bit(number: int, position: int) -> int: return int((number & (1 << position)) != 0) if __name__ == "__main__": import doctest doctest.testmod()