Prompt stringlengths 16 11.5k | Completions stringlengths 84 25.3k |
|---|---|
Write a function countleftnode returns the number of left children in the tree. For example: the following tree has four left children the nodes storing the values 6, 3, 7, and 10: 9 6 12 3 8 10 15 7 18 countleftnode 4 The tree is created for testing:... | import unittest
from bst import Node
from bst import bst
def count_left_node(root):
if root is None:
return 0
elif root.left is None:
return count_left_node(root.right)
else:
return 1 + count_left_node(root.left) + count_left_node(root.right)
"""
The tree is created for testing... |
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference possibly updated of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Note: Time complexity should be Oheight o... | class Solution(object):
def delete_node(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if not root: return None
if root.val == key:
if root.left:
# Find the right most leaf of the left sub-tree
... |
Write a function depthSum returns the sum of the values stored in a binary search tree of integers weighted by the depth of each value. For example: 9 6 12 3 8 10 15 7 18 depthsum 19 2612 3381015 4718 The tree is created for testing: 9 6 ... | import unittest
from bst import Node
from bst import bst
def depth_sum(root, n):
if root:
return recur_depth_sum(root, 1)
def recur_depth_sum(root, n):
if root is None:
return 0
elif root.left is None and root.right is None:
return root.data * n
else:
return n * root.da... |
Write a function height returns the height of a tree. The height is defined to be the number of levels. The empty tree has height 0, a tree of one node has height 1, a root node with one or two leaves as children has height 2, and so on For example: height of tree is 4 9 6 12 3 8 10 ... | import unittest
from bst import Node
from bst import bst
def height(root):
if root is None:
return 0
else:
return 1 + max(height(root.left), height(root.right))
"""
The tree is created for testing:
9
/ \
6 12
/... |
Given a binary tree, determine if it is a valid binary search tree BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also... | def is_bst(root):
"""
:type root: TreeNode
:rtype: bool
"""
stack = []
pre = None
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if pre and root.val <= pre.val:
return False
pre... |
: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()
... |
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 its... | def lowest_common_ancestor(root, p, q):
"""
:type root: Node
:type p: Node
:type q: Node
:rtype: Node
"""
while root:
if p.val > root.val < q.val:
root = root.right
elif p.val < root.val > q.val:
root = root.left
else:
return root
|
Write a function numempty returns returns the number of empty branches in a tree. Function should count the total number of empty branches among the nodes of the tree. A leaf node has two empty branches. In the case, if root is None, it considered as a 1 empty branch For example: the following tree has 10 empty branch ... | 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(r... |
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 ... | """
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) * ... |
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 postor... | class TreeNode:
def __init__(self, val, left = None, right = None):
self.val = val
self.left = left
self.right = right
pre_index = 0
def construct_tree_util(pre: list, post: list, low: int, high: int, size: int):
"""
Recursive function that constructs tree from preorde... |
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
... |
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... | class Fenwick_Tree(object):
def __init__(self, freq):
self.arr = freq
self.n = len(freq)
def get_sum(self, bit_tree, i):
"""
Returns sum of arr[0..index]. This function assumes that the array is preprocessed and partial sums of array elements are stored in bit_tree[... |
invert a binary tree | # invert a binary tree
def reverse(root):
if root is None:
return
root.left, root.right = root.right, root.left
if root.left:
reverse(root.left)
if root.right:
reverse(root.right)
|
ON solution return 0 if unbalanced else depth 1 def isbalancedroot: ON2 solution left maxheightroot.left right maxheightroot.right return absleftright 1 and isbalancedroot.left and isbalancedroot.right def maxheightroot: if root is None: return 0 return maxmaxheightroot.left, maxheightroot.right 1 | def is_balanced(root):
return __is_balanced_recursive(root)
def __is_balanced_recursive(root):
"""
O(N) solution
"""
return -1 != __get_depth(root)
def __get_depth(root):
"""
return 0 if unbalanced else depth + 1
"""
if root is None:
return 0
left = __get_depth(root.l... |
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 Retur... | 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)
q... |
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:... | # TC: O(b) SC: O(log n)
def is_symmetric(root):
if root is None:
return True
return helper(root.left, root.right)
def helper(p, q):
if p is None and q is None:
return True
if p is not None or q is not None or q.val != p.val:
return False
return helper(p.left, q.right) and h... |
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 Long... | def longest_consecutive(root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
max_len = 0
dfs(root, 0, root.val, max_len)
return max_len
def dfs(root, cur, target, max_len):
if root is None:
return
if root.val == target:
cur += 1
... |
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 ... | def lca(root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root is None or root is p or root is q:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
if left is not None and right is not None:
retur... |
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 = []
... |
:type root: TreeNode :rtype: int iterative | from tree import TreeNode
def min_depth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left is not None or root.right is not None:
return max(self.minDepth(root.left), self.minDepth(root.right))+1
return min(self.minDepth(root.left),... |
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. :t... | def has_path_sum(root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
sum -= root.val
return has_path_sum(root.left, sum) or has_path_sum(root.ri... |
Given a binary tree and a sum, find all roottoleaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum 22, 5 4 8 11 13 4 7 2 5 1 return 5,4,11,2, 5,8,4,5 DFS with stack BFS with queue | def path_sum(root, sum):
if root is None:
return []
res = []
dfs(root, sum, [], res)
return res
def dfs(root, sum, ls, res):
if root.left is None and root.right is None and root.val == sum:
ls.append(root.val)
res.append(ls)
if root.left is not None:
dfs(root.le... |
a Adam Book 4 b Bill Computer 5 TV 6 Jill Sports 1 c Bill Sports 3 d Adam Computer 3 Quin Computer 3 e Quin Book 5 TV 2 f Adam Computer 7 | # a -> Adam -> Book -> 4
# b -> Bill -> Computer -> 5
# -> TV -> 6
# Jill -> Sports -> 1
# c -> Bill -> Sports -> 3
# d -> Adam -> Computer -> 3
# Quin -> Computer -> 3
# e -> Quin -> Book -> 5
# -> TV -> 2
# f -> Adam -> Computer -> 7
from __future__ import print_function
def tree_prin... |
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... | 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):
... |
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 i... | def is_same_tree(tree_p, tree_q):
if tree_p is None and tree_q is None:
return True
if tree_p is not None and tree_q is not None and tree_p.val == tree_q.val:
return is_same_tree(tree_p.left, tree_q.left) and is_same_tree(tree_p.right, tree_q.right)
return False
# Time Complexity O(min(N,M)... |
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 Examp... | 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 * ... |
Segmenttree creates a segment tree with a given array and function, allowing queries to be done later in logN time function takes 2 values and returns a same type value Example mytree SegmentTree2,4,5,3,4,max mytree.query2,4 mytree.query0,3 ... mytree SegmentTree4,5,2,3,4,43,3,sum mytree.query1,8 ... | class SegmentTree:
def __init__(self,arr,function):
self.segment = [0 for x in range(3*len(arr)+3)]
self.arr = arr
self.fn = function
self.make_tree(0,0,len(arr)-1)
def make_tree(self,i,l,r):
if l==r:
self.segment[i] = self.arr[l]
elif l<r:
... |
Time complexity : On In order function res if not root: return res stack while root or stack: while root: stack.appendroot root root.left root stack.pop res.appendroot.val root root.right return res def inorderrecroot, resNone: | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder(root):
""" In order function """
res = []
if not root:
return res
stack = []
while root or stack:
while root:
stack.ap... |
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:
... |
Time complexity : On Recursive Implementation | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def postorder(root):
res_temp = []
res = []
if not root:
return res
stack = []
stack.append(root)
while stack:
root = stack.pop()
... |
Time complexity : On This is a class of Node def initself, val, leftNone, rightNone: self.val val self.left left self.right right def preorderroot: Recursive Implementation if root is None: return if res is None: res res.appendroot.val preorderrecroot.left, res preorderrecroot.right, res return res | class Node:
""" This is a class of Node """
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorder(root):
""" Function to Preorder """
res = []
if not root:
return res
stack = []
stack.append(root)
... |
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.... |
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... | 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):
... |
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:
curren... |
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 ... | class Union:
"""
A Union-Find data structure.
Consider the following sequence of events:
Starting with the elements 1, 2, 3, and 4:
{1} {2} {3} {4}
Initally they all live in their own sets, which means that `root(1) !=
root(3)`, however, if we call `unite(1, 3)` we would then have the... |
Get a full absolute path a file | import os
def full_path(file):
return os.path.abspath(os.path.expanduser(file))
|
Both URL and file path joins use slashes as dividers between their parts. For example: pathtodir file pathtodirfile pathtodir file pathtodirfile http:algorithms.com part http:algorithms.compart http:algorithms.com part http:algorithmspart Remove trailing Remove leading | import os
def join_with_slash(base, suffix):
# Remove / trailing
base = base.rstrip('/')
# Remove / leading
suffix = suffix.lstrip('/').rstrip()
full_path = "{}/{}".format(base, suffix)
return full_path
|
Given an absolute path for a file Unixstyle, simplify it. For example, path home, home path a.b....c, c Corner Cases: Did you consider the case where path ..? In this case, you should return . Another corner case is the path might contain multiple slashes '' together, such as homefoo. In this case, you should igno... | 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)
retu... |
Splitting a path into 2 parts Example: Input: https:algorithmsunixtest.py for url Output: part0: https:algorithmsunix part1: test.py Input: algorithmsunixtest.py for file path Output: part0: algorithmsunix part1: test.py Takt the origin path without the last part Take the last element of list | import os
def split(path):
parts = []
split_part = path.rpartition('/')
# Takt the origin path without the last part
parts.append(split_part[0])
# Take the last element of list
parts.append(split_part[2])
return parts
|
!usrbinenv python3 coding: utf8 algorithms documentation build configuration file, created by sphinxquickstart on Wed Jun 6 01:17:26 2018. This file is execfiled with the current directory set to its containing dir. Note that not all possible configuration values are present in this autogenerated file. All configura... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# algorithms documentation build configuration file, created by
# sphinx-quickstart on Wed Jun 6 01:17:26 2018.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
#... |
123, 6 123, 123 232, 8 232, 232 | from algorithms.backtrack import (
add_operators,
permute_iter,
anagram,
array_sum_combinations,
unique_array_sum_combinations,
combination_sum,
get_factors,
recursive_get_factors,
find_words,
generate_abbreviations,
generate_parenthesis_v1,
generate_parenthesis_v2,
l... |
hit hot dot dog cog pick sick sink sank tank 5 live life 1, no matter what is the wordlist. 0 length from ate ate not possible to reach ! | from algorithms.bfs import (
count_islands,
maze_search,
ladder_length
)
import unittest
class TestCountIslands(unittest.TestCase):
def test_count_islands(self):
grid_1 = [[1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]
self.assertEqual(1, count_... |
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, countonesre... | 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, s... |
summary Test for the file hosoyatriangle Arguments: unittest type description Test 1 Test 2 Test 3 Test 4 Test 5 arrange act assert arrange act assert E.g. s a b b p 1 0 0 0 a 0 1 0 0 b 0 0 1 0 0 1 1 1 | from algorithms.dp import (
max_profit_naive, max_profit_optimized,
climb_stairs, climb_stairs_optimized,
count,
combination_sum_topdown, combination_sum_bottom_up,
edit_distance,
egg_drop,
fib_recursive, fib_list, fib_iter,
hosoya_testing,
house_robber,
Job, schedule,
Item, ... |
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 ... | 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 imp... |
Test suite for the binaryheap data structures Before insert 2: 0, 4, 50, 7, 55, 90, 87 After insert: 0, 2, 50, 4, 55, 90, 87, 7 Before removemin : 0, 4, 50, 7, 55, 90, 87 After removemin: 7, 50, 87, 55, 90 Test return value Expect output | from algorithms.heap import (
BinaryHeap,
get_skyline,
max_sliding_window,
k_closest
)
import unittest
class TestBinaryHeap(unittest.TestCase):
"""
Test suite for the binary_heap data structures
"""
def setUp(self):
self.min_heap = BinaryHeap()
self.min_heap.inser... |
Test for the Iterative Segment Tree data structure Test all possible segments in the tree :param arr: array to test :param fnc: function of the segment tpree Test all possible segments in the tree with updates :param arr: array to test :param fnc: function of the segment tree :param upd: updates to test | from algorithms.tree.segment_tree.iterative_segment_tree import SegmentTree
from functools import reduce
import unittest
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
class TestSegmentTree(unittest.TestCase):
"""
Test for the Iterative Segment Tree data structure
"""
def ... |
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: 45123N... | 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_v... |
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, '... |
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 fil... | 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,
mo... |
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.cadwharderNum... | 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_... |
train set for the ANDfunction train set for light or dark colors ANDfunction darklight color test | from algorithms.ml.nearest_neighbor import (
distance,
nearest_neighbor
)
import unittest
class TestML(unittest.TestCase):
def setUp(self):
# train set for the AND-function
self.trainSetAND = {(0, 0): 0, (0, 1): 0, (1, 0): 0, (1, 1): 1}
# train set for light or dark colors
... |
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 ... | 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 ... |
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 polynomia... | 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([
Mo... |
Test suite for the Queue data structures. test iter test len test isempty test peek test dequeue test iter test len test isempty test peek test dequeue Test suite for the PriorityQueue data structures. | import unittest
from algorithms.queues import (
ArrayQueue, LinkedListQueue,
max_sliding_window,
reconstruct_queue,
PriorityQueue
)
class TestQueue(unittest.TestCase):
"""
Test suite for the Queue data structures.
"""
def test_ArrayQueue(self):
queue = ArrayQueue()
... |
Test binarysearchrecur test twosum test twosum1 test twosum2 Test find min using recursion | from algorithms.search import (
binary_search, binary_search_recur,
ternary_search,
first_occurrence,
last_occurrence,
linear_search,
search_insert,
two_sum, two_sum1, two_sum2,
search_range,
find_min_rotate, find_min_rotate_recur,
search_rotate, search_rotate_recur,
jump_sea... |
Helper function to check if the given array is sorted. :param array: Array to check if sorted :return: True if sorted in ascending order, else False printres | from algorithms.sort import (
bitonic_sort,
bogo_sort,
bubble_sort,
comb_sort,
counting_sort,
cycle_sort,
exchange_sort,
max_heap_sort, min_heap_sort,
merge_sort,
pancake_sort,
pigeonhole_sort,
quick_sort,
selection_sort,
bucket_sort,
shell_sort,
radix_sor... |
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 ... | 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.... |
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}, m... |
summary Test for the file addbinary.py Arguments: unittest type description summary Test for the file breakingbad.py Arguments: unittest type description summary Test for the file decodestring.py Arguments: unittest type description summary Test for the file deletereoccurring.py Arguments: unittest type description... | from algorithms.strings import (
add_binary,
match_symbol, match_symbol_1, bracket,
decode_string,
delete_reoccurring_characters,
domain_name_1, domain_name_2,
encode, decode,
group_anagrams,
int_to_roman,
is_palindrome, is_palindrome_reverse,
is_palindrome_two_pointer, is_palind... |
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
im... |
Test full path relative Test full path with expanding user filename Test url path Test file path | from algorithms.unix import (
join_with_slash,
full_path,
split,
simplify_path_v1, simplify_path_v2
)
import os
import unittest
class TestUnixPath(unittest.TestCase):
def test_join_with_slash(self):
self.assertEqual("path/to/dir/file",
join_with_slash("path/to/dir/... |
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: NORMALIZE... | from math import cos, sin, sqrt, tau
from audio_filters.iir_filter import IIRFilter
"""
Create 2nd-order IIR filters with Butterworth design.
Code based on https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html
Alternatively you can use scipy.signal.butter, which should yield the same results.
"""
def... |
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.orde... | from __future__ import annotations
class IIRFilter:
r"""
N-Order IIR filter
Assumes working with float samples normalized on [-1, 1]
---
Implementation details:
Based on the 2nd-order function from
https://en.wikipedia.org/wiki/Digital_biquad_filter,
this generalized N-order functio... |
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... | from __future__ import annotations
from math import pi
from typing import Protocol
import matplotlib.pyplot as plt
import numpy as np
class FilterType(Protocol):
def process(self, sample: float) -> float:
"""
Calculate y[n]
>>> issubclass(FilterType, Protocol)
True
"""
... |
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 ... | from __future__ import annotations
from itertools import combinations
def combination_lists(n: int, k: int) -> list[list[int]]:
"""
>>> combination_lists(n=4, k=2)
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
"""
return [list(x) for x in combinations(range(1, n + 1), k)]
def generate_all_co... |
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 lensequenc... | 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... |
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.... | from __future__ import annotations
from typing import Any
def generate_all_subsequences(sequence: list[Any]) -> None:
create_state_space_tree(sequence, [], 0)
def create_state_space_tree(
sequence: list[Any], current_subsequence: list[Any], index: int
) -> None:
"""
Creates a state space tree to it... |
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 constrai... | def valid_coloring(
neighbours: list[int], colored_vertices: list[int], color: int
) -> bool:
"""
For each neighbour check if the coloring constraint is satisfied
If any of the neighbours fail the constraint return False
If all neighbours validate the constraint return True
>>> neighbours = [0,... |
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 distin... | def backtrack(
candidates: list, path: list, answer: list, target: int, previous_index: int
) -> None:
"""
A recursive function that searches for possible combinations. Backtracks in case
of a bigger current combination value than the target value.
Parameters
----------
previous_index: Last... |
https:www.geeksforgeeks.orgsolvecrosswordpuzzle Check if a word can be placed at the given position. puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... isvalidpuzzle, 'word', 0, 0, True True puzzle ... '', '', '', '', ... '', '', '', '', ... '',... | # https://www.geeksforgeeks.org/solve-crossword-puzzle/
def is_valid(
puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool
) -> bool:
"""
Check if a word can be placed at the given position.
>>> puzzle = [
... ['', '', '', ''],
... ['', '', '', ''],
... ['', ... |
author: Aayush Soni Given n pairs of parentheses, write a function to generate all combinations of wellformed parentheses. Input: n 2 Output: , Leetcode link: https:leetcode.comproblemsgenerateparenthesesdescription Generate valid combinations of balanced parentheses using recursion. :param partial: A string represent... | def backtrack(
partial: str, open_count: int, close_count: int, n: int, result: list[str]
) -> None:
"""
Generate valid combinations of balanced parentheses using recursion.
:param partial: A string representing the current combination.
:param open_count: An integer representing the count of open p... |
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 in... | def valid_connection(
graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int]
) -> bool:
"""
Checks whether it is possible to add next into path by validating 2 statements
1. There should be path between current and next vertex
2. Next vertex should not be in path
If both validatio... |
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 kni... | # Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM
from __future__ import annotations
def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]:
"""
Find all the valid positions a knight can move to from the current position.
>>> get_valid_pos((1, 3), 4)
[(2, 1), (0... |
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 matchwordpattern... | def match_word_pattern(pattern: str, input_string: str) -> bool:
"""
Determine if a given pattern matches a string using backtracking.
pattern: The pattern to match.
input_string: The string to match against the pattern.
return: True if the pattern matches the string, False otherwise.
>>> matc... |
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 min... | from __future__ import annotations
import math
def minimax(
depth: int, node_index: int, is_max: bool, scores: list[int], height: float
) -> int:
"""
This function implements the minimax algorithm, which helps achieve the optimal
score for a player in a two-player game by checking all possible moves.... |
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 ther... | from __future__ import annotations
solution = []
def is_safe(board: list[list[int]], row: int, column: int) -> bool:
"""
This function returns a boolean value True if it is safe to place a queen there
considering the current state of the board.
Parameters:
board (2D matrix): The chessboard
r... |
from future import annotations def depthfirstsearch possibleboard: listint, diagonalrightcollisions: listint, diagonalleftcollisions: listint, boards: listliststr, n: int, None: Get next row in the current board possibleboard to fill it with a queen row lenpossibleboard If row is equal to the size of the board it me... | r"""
Problem:
The n queens problem is: placing N queens on a N * N chess board such that no queen
can attack any other queens placed on that chess board. This means that one queen
cannot have any other queen on its horizontal, vertical and diagonal lines.
Solution:
To solve this problem we will use simple math. Fir... |
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. Constr... | def backtrack(
needed_sum: int,
power: int,
current_number: int,
current_sum: int,
solutions_count: int,
) -> tuple[int, int]:
"""
>>> backtrack(13, 2, 1, 0, 0)
(0, 1)
>>> backtrack(10, 2, 1, 0, 0)
(0, 1)
>>> backtrack(10, 3, 1, 0, 0)
(0, 0)
>>> backtrack(20, 2, 1, 0,... |
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 destina... | from __future__ import annotations
def solve_maze(
maze: list[list[int]],
source_row: int,
source_column: int,
destination_row: int,
destination_column: int,
) -> list[list[int]]:
"""
This method solves the "rat in maze" problem.
Parameters :
- maze: A two dimensional matrix of... |
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 recursive... | from __future__ import annotations
Matrix = list[list[int]]
# assigning initial values to the grid
initial_grid: Matrix = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, ... |
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... | 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)
... |
Author : Alexander Pantyukhin Date : November 24, 2022 Task: Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter ce... | def get_point_key(len_board: int, len_board_column: int, row: int, column: int) -> int:
"""
Returns the hash key of matrix indexes.
>>> get_point_key(10, 20, 1, 0)
200
"""
return len_board * len_board_column * row + column
def exits_word(
board: list[list[str]],
word: str,
row: i... |
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' binary... | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
def binary_and(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary and operation on the integers provided.
>>> binary_and(25, 32)
'0b000000'
>>>... |
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' binarycodeddecima... | def binary_coded_decimal(number: int) -> str:
"""
Find binary coded decimal (bcd) of integer base 10.
Each digit of the number is represented by a 4-bit binary.
Example:
>>> binary_coded_decimal(-2)
'0b0000'
>>> binary_coded_decimal(-1)
'0b0000'
>>> binary_coded_decimal(0)
'0b000... |
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: ... ValueEr... | def binary_count_setbits(a: int) -> int:
"""
Take in 1 integer, return a number that is
the number of 1's in binary representation of that number.
>>> binary_count_setbits(25)
3
>>> binary_count_setbits(36)
2
>>> binary_count_setbits(16)
1
>>> binary_count_setbits(58)
4
... |
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 binarycounttrailin... | from math import log2
def binary_count_trailing_zeros(a: int) -> int:
"""
Take in 1 integer, return a number that is
the number of trailing zeros in binary representation of that number.
>>> binary_count_trailing_zeros(25)
0
>>> binary_count_trailing_zeros(36)
2
>>> binary_count_trail... |
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' binaryo... | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
def binary_or(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary, and return a binary number that is the
result of a binary or operation on the integers provided.
>>> binary_or(25, 32)
'0b111001'
>>> bi... |
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.... | # Information on binary shifts:
# https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types
# https://www.interviewcake.com/concept/java/bit-shift
def logical_left_shift(number: int, shift_amount: int) -> str:
"""
Take in 2 positive integers.
'number' is the integer to be logical... |
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 T... | # Information on 2's complement: https://en.wikipedia.org/wiki/Two%27s_complement
def twos_complement(number: int) -> str:
"""
Take in a negative integer 'number'.
Return the two's complement representation of 'number'.
>>> twos_complement(0)
'0b0'
>>> twos_complement(-1)
'0b11'
>>> t... |
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' binary... | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
def binary_xor(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary xor operation on the integers provided.
>>> binary_xor(25, 32)
'0b111001'
>>>... |
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 argum... | def bitwise_addition_recursive(number: int, other_number: int) -> int:
"""
>>> bitwise_addition_recursive(4, 5)
9
>>> bitwise_addition_recursive(8, 9)
17
>>> bitwise_addition_recursive(0, 4)
4
>>> bitwise_addition_recursive(4.5, 9)
Traceback (most recent call last):
...
T... |
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... | def get_1s_count(number: int) -> int:
"""
Count the number of set bits in a 32 bit integer using Brian Kernighan's way.
Ref - https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
>>> get_1s_count(25)
3
>>> get_1s_count(37)
3
>>> get_1s_count(21)
3
>>> get_1s... |
Count the number of set bits in a 32 bit integer getsetbitscountusingbriankernighansalgorithm25 3 getsetbitscountusingbriankernighansalgorithm37 3 getsetbitscountusingbriankernighansalgorithm21 3 getsetbitscountusingbriankernighansalgorithm58 4 getsetbitscountusingbriankernighansalgorithm0 0 getsetbitscountusingb... | from timeit import timeit
def get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int:
"""
Count the number of set bits in a 32 bit integer
>>> get_set_bits_count_using_brian_kernighans_algorithm(25)
3
>>> get_set_bits_count_using_brian_kernighans_algorithm(37)
3
>>> get_se... |
Find excess3 code of integer base 10. Add 3 to all digits in a decimal number then convert to a binarycoded decimal. https:en.wikipedia.orgwikiExcess3 excess3code0 '0b0011' excess3code3 '0b0110' excess3code2 '0b0101' excess3code20 '0b01010011' excess3code120 '0b010001010011' | def excess_3_code(number: int) -> str:
"""
Find excess-3 code of integer base 10.
Add 3 to all digits in a decimal number then convert to a binary-coded decimal.
https://en.wikipedia.org/wiki/Excess-3
>>> excess_3_code(0)
'0b0011'
>>> excess_3_code(3)
'0b0110'
>>> excess_3_code(2)
... |
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 inte... | def find_previous_power_of_two(number: int) -> int:
"""
Find the largest power of two that is less than or equal to a given integer.
https://stackoverflow.com/questions/1322510
>>> [find_previous_power_of_two(i) for i in range(18)]
[0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16]
>>> fi... |
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 exactl... | def gray_code(bit_count: int) -> list:
"""
Takes in an integer n and returns a n-bit
gray code sequence
An n-bit gray code sequence is a sequence of 2^n
integers where:
a) Every integer is between [0,2^n -1] inclusive
b) The sequence begins with 0
c) An integer appears at most one times... |
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... | def get_highest_set_bit_position(number: int) -> int:
"""
Returns position of the highest set bit of a number.
Ref - https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
>>> get_highest_set_bit_position(25)
5
>>> get_highest_set_bit_position(37)
6
>>> get_highest_set_bi... |
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 getindexofrightmostse... | # Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/
def get_index_of_rightmost_set_bit(number: int) -> int:
"""
Take in a positive integer 'number'.
Returns the zero-based index of first set bit in that 'number' from right.
Returns -1, If no set bit found.
>>> get_index_of_r... |
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 ... | def is_even(number: int) -> bool:
"""
return true if the input integer is even
Explanation: Lets take a look at the following decimal to binary conversions
2 => 10
14 => 1110
100 => 1100100
3 => 11
13 => 1101
101 => 1100101
from the above examples we can observe that
for all ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.