Prompt
stringlengths
16
11.5k
Completions
stringlengths
84
25.3k
Get the Next Greatest Element NGE for all elements in a list. Maximum element present after the current one which is also greater than the current one. nextgreatestelementslowarr expect True Like nextgreatestelementslow but changes the loops to use enumerate instead of rangelen for the outer loop and for in a slice of arr for the inner loop. nextgreatestelementfastarr expect True Get the Next Greatest Element NGE for all elements in a list. Maximum element present after the current one which is also greater than the current one. A naive way to solve this is to take two loops and check for the next bigger number but that will make the time complexity as On2. The better way to solve this would be to use a stack to keep track of maximum number giving a linear time solution. nextgreatestelementarr expect True
from __future__ import annotations arr = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] expect = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def next_greatest_element_slow(arr: list[float]) -> list[float]: """ Get the Next Greatest Element (NGE) for all elements in a list. Maximum element present after the current one which is also greater than the current one. >>> next_greatest_element_slow(arr) == expect True """ result = [] arr_size = len(arr) for i in range(arr_size): next_element: float = -1 for j in range(i + 1, arr_size): if arr[i] < arr[j]: next_element = arr[j] break result.append(next_element) return result def next_greatest_element_fast(arr: list[float]) -> list[float]: """ Like next_greatest_element_slow() but changes the loops to use enumerate() instead of range(len()) for the outer loop and for in a slice of arr for the inner loop. >>> next_greatest_element_fast(arr) == expect True """ result = [] for i, outer in enumerate(arr): next_item: float = -1 for inner in arr[i + 1 :]: if outer < inner: next_item = inner break result.append(next_item) return result def next_greatest_element(arr: list[float]) -> list[float]: """ Get the Next Greatest Element (NGE) for all elements in a list. Maximum element present after the current one which is also greater than the current one. A naive way to solve this is to take two loops and check for the next bigger number but that will make the time complexity as O(n^2). The better way to solve this would be to use a stack to keep track of maximum number giving a linear time solution. >>> next_greatest_element(arr) == expect True """ arr_size = len(arr) stack: list[float] = [] result: list[float] = [-1] * arr_size for index in reversed(range(arr_size)): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: result[index] = stack[-1] stack.append(arr[index]) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) setup = ( "from __main__ import arr, next_greatest_element_slow, " "next_greatest_element_fast, next_greatest_element" ) print( "next_greatest_element_slow():", timeit("next_greatest_element_slow(arr)", setup=setup), ) print( "next_greatest_element_fast():", timeit("next_greatest_element_fast(arr)", setup=setup), ) print( " next_greatest_element():", timeit("next_greatest_element(arr)", setup=setup), )
Reverse Polish Nation is also known as Polish postfix notation or simply postfix notation. https:en.wikipedia.orgwikiReversePolishnotation Classic examples of simple stack implementations. Valid operators are , , , . Each operand may be an integer or another expression. Output: Enter a Postfix Equation space separated 5 6 9 Symbol Action Stack 5 push5 5 6 push6 5,6 9 push9 5,6,9 pop9 5,6 pop6 5 push69 5,54 pop54 5 pop5 push554 59 Result 59 Defining valid unary operator symbols operators their respective operation Converts the given data to the appropriate number if it is indeed a number, else returns the data as it is with a False flag. This function also serves as a check of whether the input is a number or not. Parameters token: The data that needs to be converted to the appropriate operator or number. Returns float or str Returns a float if token is a number or a str if token is an operator Evaluate postfix expression using a stack. evaluate0 0.0 evaluate0 0.0 evaluate1 1.0 evaluate1 1.0 evaluate1.1 1.1 evaluate2, 1, , 3, 9.0 evaluate2, 1.9, , 3, 11.7 evaluate2, 1.9, , 3, 0.30000000000000027 evaluate4, 13, 5, , 6.6 evaluate2, , 3, 1.0 evaluate4, 5, , 6, 26.0 evaluate 0 evaluate4, , 6, 7, , 9, 8 Traceback most recent call last: ... ArithmeticError: Input is not a valid postfix expression Parameters postfix: The postfix expression is tokenized into operators and operands and stored as a Python list verbose: Display stack contents while evaluating the expression if verbose is True Returns float The evaluated value Checking the list to find out whether the postfix expression is valid print table header output in tabular format If x is operator If only 1 value is inside the stack and or is encountered then this is unary or case output in tabular format output in tabular format output in tabular format evaluate the 2 values popped from stack push result to stack output in tabular format If everything is executed correctly, the stack will contain only one element which is the result Create a loop so that the user can evaluate postfix expressions multiple times
# Defining valid unary operator symbols UNARY_OP_SYMBOLS = ("-", "+") # operators & their respective operation OPERATORS = { "^": lambda p, q: p**q, "*": lambda p, q: p * q, "/": lambda p, q: p / q, "+": lambda p, q: p + q, "-": lambda p, q: p - q, } def parse_token(token: str | float) -> float | str: """ Converts the given data to the appropriate number if it is indeed a number, else returns the data as it is with a False flag. This function also serves as a check of whether the input is a number or not. Parameters ---------- token: The data that needs to be converted to the appropriate operator or number. Returns ------- float or str Returns a float if `token` is a number or a str if `token` is an operator """ if token in OPERATORS: return token try: return float(token) except ValueError: msg = f"{token} is neither a number nor a valid operator" raise ValueError(msg) def evaluate(post_fix: list[str], verbose: bool = False) -> float: """ Evaluate postfix expression using a stack. >>> evaluate(["0"]) 0.0 >>> evaluate(["-0"]) -0.0 >>> evaluate(["1"]) 1.0 >>> evaluate(["-1"]) -1.0 >>> evaluate(["-1.1"]) -1.1 >>> evaluate(["2", "1", "+", "3", "*"]) 9.0 >>> evaluate(["2", "1.9", "+", "3", "*"]) 11.7 >>> evaluate(["2", "-1.9", "+", "3", "*"]) 0.30000000000000027 >>> evaluate(["4", "13", "5", "/", "+"]) 6.6 >>> evaluate(["2", "-", "3", "+"]) 1.0 >>> evaluate(["-4", "5", "*", "6", "-"]) -26.0 >>> evaluate([]) 0 >>> evaluate(["4", "-", "6", "7", "/", "9", "8"]) Traceback (most recent call last): ... ArithmeticError: Input is not a valid postfix expression Parameters ---------- post_fix: The postfix expression is tokenized into operators and operands and stored as a Python list verbose: Display stack contents while evaluating the expression if verbose is True Returns ------- float The evaluated value """ if not post_fix: return 0 # Checking the list to find out whether the postfix expression is valid valid_expression = [parse_token(token) for token in post_fix] if verbose: # print table header print("Symbol".center(8), "Action".center(12), "Stack", sep=" | ") print("-" * (30 + len(post_fix))) stack = [] for x in valid_expression: if x not in OPERATORS: stack.append(x) # append x to stack if verbose: # output in tabular format print( f"{x}".rjust(8), f"push({x})".ljust(12), stack, sep=" | ", ) continue # If x is operator # If only 1 value is inside the stack and + or - is encountered # then this is unary + or - case if x in UNARY_OP_SYMBOLS and len(stack) < 2: b = stack.pop() # pop stack if x == "-": b *= -1 # negate b stack.append(b) if verbose: # output in tabular format print( "".rjust(8), f"pop({b})".ljust(12), stack, sep=" | ", ) print( str(x).rjust(8), f"push({x}{b})".ljust(12), stack, sep=" | ", ) continue b = stack.pop() # pop stack if verbose: # output in tabular format print( "".rjust(8), f"pop({b})".ljust(12), stack, sep=" | ", ) a = stack.pop() # pop stack if verbose: # output in tabular format print( "".rjust(8), f"pop({a})".ljust(12), stack, sep=" | ", ) # evaluate the 2 values popped from stack & push result to stack stack.append(OPERATORS[x](a, b)) # type: ignore[index] if verbose: # output in tabular format print( f"{x}".rjust(8), f"push({a}{x}{b})".ljust(12), stack, sep=" | ", ) # If everything is executed correctly, the stack will contain # only one element which is the result if len(stack) != 1: raise ArithmeticError("Input is not a valid postfix expression") return float(stack[0]) if __name__ == "__main__": # Create a loop so that the user can evaluate postfix expressions multiple times while True: expression = input("Enter a Postfix Expression (space separated): ").split(" ") prompt = "Do you want to see stack contents while evaluating? [y/N]: " verbose = input(prompt).strip().lower() == "y" output = evaluate(expression, verbose) print("Result = ", output) prompt = "Do you want to enter another expression? [y/N]: " if input(prompt).strip().lower() != "y": break
Python3 program to evaluate a prefix expression. Return True if the given char c is an operand, e.g. it is a number isoperand1 True isoperand False Evaluate a given expression in prefix notation. Asserts that the given expression is valid. evaluate 9 2 6 21 evaluate 10 2 4 1 4.0 iterate over the string in reverse order push operand to stack pop values from stack can calculate the result push the result onto the stack again Driver code
calc = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y, } def is_operand(c): """ Return True if the given char c is an operand, e.g. it is a number >>> is_operand("1") True >>> is_operand("+") False """ return c.isdigit() def evaluate(expression): """ Evaluate a given expression in prefix notation. Asserts that the given expression is valid. >>> evaluate("+ 9 * 2 6") 21 >>> evaluate("/ * 10 2 + 4 1 ") 4.0 """ stack = [] # iterate over the string in reverse order for c in expression.split()[::-1]: # push operand to stack if is_operand(c): stack.append(int(c)) else: # pop values from stack can calculate the result # push the result onto the stack again o1 = stack.pop() o2 = stack.pop() stack.append(calc[c](o1, o2)) return stack.pop() # Driver code if __name__ == "__main__": test_expression = "+ 9 * 2 6" print(evaluate(test_expression)) test_expression = "/ * 10 2 + 4 1 " print(evaluate(test_expression))
A stack is an abstract data type that serves as a collection of elements with two principal operations: push and pop. push adds an element to the top of the stack, and pop removes an element from the top of a stack. The order in which elements come off of a stack are Last In, First Out LIFO. https:en.wikipedia.orgwikiStackabstractdatatype Push an element to the top of the stack. S Stack2 stack size 2 S.push10 S.push20 printS 10, 20 S Stack1 stack size 1 S.push10 S.push20 Traceback most recent call last: ... datastructures.stacks.stack.StackOverflowError Pop an element off of the top of the stack. S Stack S.push5 S.push10 S.pop 10 Stack.pop Traceback most recent call last: ... datastructures.stacks.stack.StackUnderflowError Peek at the topmost element of the stack. S Stack S.push5 S.push10 S.peek 10 Stack.peek Traceback most recent call last: ... datastructures.stacks.stack.StackUnderflowError Check if a stack is empty. S Stack S.isempty True S Stack S.push10 S.isempty False S Stack S.isfull False S Stack1 S.push10 S.isfull True Return the size of the stack. S Stack3 S.size 0 S Stack3 S.push10 S.size 1 S Stack3 S.push10 S.push20 S.size 2 Check if item is in stack S Stack3 S.push10 10 in S True S Stack3 S.push10 20 in S False teststack
from __future__ import annotations from typing import Generic, TypeVar T = TypeVar("T") class StackOverflowError(BaseException): pass class StackUnderflowError(BaseException): pass class Stack(Generic[T]): """A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top of a stack. The order in which elements come off of a stack are Last In, First Out (LIFO). https://en.wikipedia.org/wiki/Stack_(abstract_data_type) """ def __init__(self, limit: int = 10): self.stack: list[T] = [] self.limit = limit def __bool__(self) -> bool: return bool(self.stack) def __str__(self) -> str: return str(self.stack) def push(self, data: T) -> None: """ Push an element to the top of the stack. >>> S = Stack(2) # stack size = 2 >>> S.push(10) >>> S.push(20) >>> print(S) [10, 20] >>> S = Stack(1) # stack size = 1 >>> S.push(10) >>> S.push(20) Traceback (most recent call last): ... data_structures.stacks.stack.StackOverflowError """ if len(self.stack) >= self.limit: raise StackOverflowError self.stack.append(data) def pop(self) -> T: """ Pop an element off of the top of the stack. >>> S = Stack() >>> S.push(-5) >>> S.push(10) >>> S.pop() 10 >>> Stack().pop() Traceback (most recent call last): ... data_structures.stacks.stack.StackUnderflowError """ if not self.stack: raise StackUnderflowError return self.stack.pop() def peek(self) -> T: """ Peek at the top-most element of the stack. >>> S = Stack() >>> S.push(-5) >>> S.push(10) >>> S.peek() 10 >>> Stack().peek() Traceback (most recent call last): ... data_structures.stacks.stack.StackUnderflowError """ if not self.stack: raise StackUnderflowError return self.stack[-1] def is_empty(self) -> bool: """ Check if a stack is empty. >>> S = Stack() >>> S.is_empty() True >>> S = Stack() >>> S.push(10) >>> S.is_empty() False """ return not bool(self.stack) def is_full(self) -> bool: """ >>> S = Stack() >>> S.is_full() False >>> S = Stack(1) >>> S.push(10) >>> S.is_full() True """ return self.size() == self.limit def size(self) -> int: """ Return the size of the stack. >>> S = Stack(3) >>> S.size() 0 >>> S = Stack(3) >>> S.push(10) >>> S.size() 1 >>> S = Stack(3) >>> S.push(10) >>> S.push(20) >>> S.size() 2 """ return len(self.stack) def __contains__(self, item: T) -> bool: """ Check if item is in stack >>> S = Stack(3) >>> S.push(10) >>> 10 in S True >>> S = Stack(3) >>> S.push(10) >>> 20 in S False """ return item in self.stack def test_stack() -> None: """ >>> test_stack() """ stack: Stack[int] = Stack(10) assert bool(stack) is False assert stack.is_empty() is True assert stack.is_full() is False assert str(stack) == "[]" try: _ = stack.pop() raise AssertionError # This should not happen except StackUnderflowError: assert True # This should happen try: _ = stack.peek() raise AssertionError # This should not happen except StackUnderflowError: assert True # This should happen for i in range(10): assert stack.size() == i stack.push(i) assert bool(stack) assert not stack.is_empty() assert stack.is_full() assert str(stack) == str(list(range(10))) assert stack.pop() == 9 assert stack.peek() == 8 stack.push(100) assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100]) try: stack.push(200) raise AssertionError # This should not happen except StackOverflowError: assert True # This should happen assert not stack.is_empty() assert stack.size() == 10 assert 5 in stack assert 55 not in stack if __name__ == "__main__": test_stack() import doctest doctest.testmod()
https:www.geeksforgeeks.orgimplementstackusingqueue stack StackWithQueues stack.push1 stack.push2 stack.push3 stack.peek 3 stack.pop 3 stack.peek 2 stack.pop 2 stack.pop 1 stack.peek is None True stack.pop Traceback most recent call last: ... IndexError: pop from an empty deque
from __future__ import annotations from collections import deque from dataclasses import dataclass, field @dataclass class StackWithQueues: """ https://www.geeksforgeeks.org/implement-stack-using-queue/ >>> stack = StackWithQueues() >>> stack.push(1) >>> stack.push(2) >>> stack.push(3) >>> stack.peek() 3 >>> stack.pop() 3 >>> stack.peek() 2 >>> stack.pop() 2 >>> stack.pop() 1 >>> stack.peek() is None True >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from an empty deque """ main_queue: deque[int] = field(default_factory=deque) temp_queue: deque[int] = field(default_factory=deque) def push(self, item: int) -> None: self.temp_queue.append(item) while self.main_queue: self.temp_queue.append(self.main_queue.popleft()) self.main_queue, self.temp_queue = self.temp_queue, self.main_queue def pop(self) -> int: return self.main_queue.popleft() def peek(self) -> int | None: return self.main_queue[0] if self.main_queue else None if __name__ == "__main__": import doctest doctest.testmod() stack: StackWithQueues | None = StackWithQueues() while stack: print("\nChoose operation:") print("1. Push") print("2. Pop") print("3. Peek") print("4. Quit") choice = input("Enter choice (1/2/3/4): ") if choice == "1": element = int(input("Enter an integer to push: ").strip()) stack.push(element) print(f"{element} pushed onto the stack.") elif choice == "2": popped_element = stack.pop() if popped_element is not None: print(f"Popped element: {popped_element}") else: print("Stack is empty.") elif choice == "3": peeked_element = stack.peek() if peeked_element is not None: print(f"Top element: {peeked_element}") else: print("Stack is empty.") elif choice == "4": del stack stack = None else: print("Invalid choice. Please try again.")
A complete working Python program to demonstrate all stack operations using a doubly linked list stack Stack stack.isempty True stack.printstack stack elements are: for i in range4: ... stack.pushi ... stack.isempty False stack.printstack stack elements are: 3210 stack.top 3 lenstack 4 stack.pop 3 stack.printstack stack elements are: 210 add a Node to the stack if self.head is None: self.head Nodedata else: newnode Nodedata self.head.prev newnode newnode.next self.head newnode.prev None self.head newnode def popself T None: return the top element of the stack return self.head.data if self.head is not None else None def lenself int: temp self.head count 0 while temp is not None: count 1 temp temp.next return count def isemptyself bool: return self.head is None def printstackself None: printstack elements are: temp self.head while temp is not None: printtemp.data, end temp temp.next Code execution starts here if name main: Start with the empty stack stack: Stackint Stack Insert 4 at the beginning. So stack becomes 4None printStack operations using Doubly LinkedList stack.push4 Insert 5 at the beginning. So stack becomes 45None stack.push5 Insert 6 at the beginning. So stack becomes 456None stack.push6 Insert 7 at the beginning. So stack becomes 4567None stack.push7 Print the stack stack.printstack Print the top element printnTop element is , stack.top Print the stack size printSize of the stack is , lenstack pop the top element stack.pop pop the top element stack.pop two elements have now been popped off stack.printstack Print True if the stack is empty else False printnstack is empty:, stack.isempty
# A complete working Python program to demonstrate all # stack operations using a doubly linked list from __future__ import annotations from typing import Generic, TypeVar T = TypeVar("T") class Node(Generic[T]): def __init__(self, data: T): self.data = data # Assign data self.next: Node[T] | None = None # Initialize next as null self.prev: Node[T] | None = None # Initialize prev as null class Stack(Generic[T]): """ >>> stack = Stack() >>> stack.is_empty() True >>> stack.print_stack() stack elements are: >>> for i in range(4): ... stack.push(i) ... >>> stack.is_empty() False >>> stack.print_stack() stack elements are: 3->2->1->0-> >>> stack.top() 3 >>> len(stack) 4 >>> stack.pop() 3 >>> stack.print_stack() stack elements are: 2->1->0-> """ def __init__(self) -> None: self.head: Node[T] | None = None def push(self, data: T) -> None: """add a Node to the stack""" if self.head is None: self.head = Node(data) else: new_node = Node(data) self.head.prev = new_node new_node.next = self.head new_node.prev = None self.head = new_node def pop(self) -> T | None: """pop the top element off the stack""" if self.head is None: return None else: assert self.head is not None temp = self.head.data self.head = self.head.next if self.head is not None: self.head.prev = None return temp def top(self) -> T | None: """return the top element of the stack""" return self.head.data if self.head is not None else None def __len__(self) -> int: temp = self.head count = 0 while temp is not None: count += 1 temp = temp.next return count def is_empty(self) -> bool: return self.head is None def print_stack(self) -> None: print("stack elements are:") temp = self.head while temp is not None: print(temp.data, end="->") temp = temp.next # Code execution starts here if __name__ == "__main__": # Start with the empty stack stack: Stack[int] = Stack() # Insert 4 at the beginning. So stack becomes 4->None print("Stack operations using Doubly LinkedList") stack.push(4) # Insert 5 at the beginning. So stack becomes 4->5->None stack.push(5) # Insert 6 at the beginning. So stack becomes 4->5->6->None stack.push(6) # Insert 7 at the beginning. So stack becomes 4->5->6->7->None stack.push(7) # Print the stack stack.print_stack() # Print the top element print("\nTop element is ", stack.top()) # Print the stack size print("Size of the stack is ", len(stack)) # pop the top element stack.pop() # pop the top element stack.pop() # two elements have now been popped off stack.print_stack() # Print True if the stack is empty else False print("\nstack is empty:", stack.is_empty())
A Stack using a linked list like structure from future import annotations from collections.abc import Iterator from typing import Generic, TypeVar T TypeVarT class NodeGenericT: def initself, data: T: self.data data self.next: NodeT None None def strself str: return fself.data class LinkedStackGenericT: def initself None: self.top: NodeT None None def iterself IteratorT: node self.top while node: yield node.data node node.next def strself str: return .joinstritem for item in self def lenself int: return lentupleiterself def isemptyself bool: return self.top is None def pushself, item: T None: node Nodeitem if not self.isempty: node.next self.top self.top node def popself T: if self.isempty: raise IndexErrorpop from empty stack assert isinstanceself.top, Node popnode self.top self.top self.top.next return popnode.data def peekself T: if self.isempty: raise IndexErrorpeek from empty stack assert self.top is not None return self.top.data def clearself None: self.top None if name main: from doctest import testmod testmod
from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar T = TypeVar("T") class Node(Generic[T]): def __init__(self, data: T): self.data = data self.next: Node[T] | None = None def __str__(self) -> str: return f"{self.data}" class LinkedStack(Generic[T]): """ Linked List Stack implementing push (to top), pop (from top) and is_empty >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(5) >>> stack.push(9) >>> stack.push('python') >>> stack.is_empty() False >>> stack.pop() 'python' >>> stack.push('algorithms') >>> stack.pop() 'algorithms' >>> stack.pop() 9 >>> stack.pop() 5 >>> stack.is_empty() True >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack """ def __init__(self) -> None: self.top: Node[T] | None = None def __iter__(self) -> Iterator[T]: node = self.top while node: yield node.data node = node.next def __str__(self) -> str: """ >>> stack = LinkedStack() >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> str(stack) 'a->b->c' """ return "->".join([str(item) for item in self]) def __len__(self) -> int: """ >>> stack = LinkedStack() >>> len(stack) == 0 True >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> len(stack) == 3 True """ return len(tuple(iter(self))) def is_empty(self) -> bool: """ >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(1) >>> stack.is_empty() False """ return self.top is None def push(self, item: T) -> None: """ >>> stack = LinkedStack() >>> stack.push("Python") >>> stack.push("Java") >>> stack.push("C") >>> str(stack) 'C->Java->Python' """ node = Node(item) if not self.is_empty(): node.next = self.top self.top = node def pop(self) -> T: """ >>> stack = LinkedStack() >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> stack.pop() == 'a' True >>> stack.pop() == 'b' True >>> stack.pop() == 'c' True """ if self.is_empty(): raise IndexError("pop from empty stack") assert isinstance(self.top, Node) pop_node = self.top self.top = self.top.next return pop_node.data def peek(self) -> T: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> stack.peek() 'Python' """ if self.is_empty(): raise IndexError("peek from empty stack") assert self.top is not None return self.top.data def clear(self) -> None: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> str(stack) 'Python->C->Java' >>> stack.clear() >>> len(stack) == 0 True """ self.top = None if __name__ == "__main__": from doctest import testmod testmod()
The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock's price for all n days. The span Si of the stock's price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day. Create a stack and push index of fist element to it Span value of first element is always 1 Calculate span values for rest of the elements Pop elements from stack while stack is not empty and top of stack is smaller than pricei If stack becomes empty, then pricei is greater than all elements on left of it, i.e. price0, price1, ..pricei1. Else the pricei is greater than elements after top of stack Push this element to stack A utility function to print elements of array Driver program to test above function Fill the span values in array S Print the calculated span values
def calculation_span(price, s): n = len(price) # Create a stack and push index of fist element to it st = [] st.append(0) # Span value of first element is always 1 s[0] = 1 # Calculate span values for rest of the elements for i in range(1, n): # Pop elements from stack while stack is not # empty and top of stack is smaller than price[i] while len(st) > 0 and price[st[0]] <= price[i]: st.pop() # If stack becomes empty, then price[i] is greater # than all elements on left of it, i.e. price[0], # price[1], ..price[i-1]. Else the price[i] is # greater than elements after top of stack s[i] = i + 1 if len(st) <= 0 else (i - st[0]) # Push this element to stack st.append(i) # A utility function to print elements of array def print_array(arr, n): for i in range(n): print(arr[i], end=" ") # Driver program to test above function price = [10, 4, 5, 90, 120, 80] S = [0 for i in range(len(price) + 1)] # Fill the span values in array S[] calculation_span(price, S) # Print the calculated span values print_array(S, len(price))
A Radix Tree is a data structure that represents a spaceoptimized trie prefix tree in whicheach node that is the only child is merged with its parent https:en.wikipedia.orgwikiRadixtree Mapping from the first character of the prefix of the node A node will be a leaf if the tree contains its word Compute the common substring of the prefix of the node and a word Args: word str: word to compare Returns: str, str, str: common substring, remaining prefix, remaining word RadixNodemyprefix.matchmystring 'my', 'prefix', 'string' Insert many words in the tree Args: words liststr: list of words RadixNodemyprefix.insertmanymystring, hello Insert a word into the tree Args: word str: word to insert RadixNodemyprefix.insertmystring root RadixNode root.insertmany'myprefix', 'myprefixA', 'myprefixAA' root.printtree myprefix leaf A leaf A leaf Case 1: If the word is the prefix of the node Solution: We set the current node as leaf Case 2: The node has no edges that have a prefix to the word Solution: We create an edge from the current node to a new one containing the word Case 3: The node prefix is equal to the matching Solution: We insert remaining word on the next node Case 4: The word is greater equal to the matching Solution: Create a node in between both nodes, change prefixes and add the new node for the remaining word Returns if the word is on the tree Args: word str: word to check Returns: bool: True if the word appears on the tree RadixNodemyprefix.findmystring False If there is remaining prefix, the word can't be on the tree This applies when the word and the prefix are equal We have word remaining so we check the next node Deletes a word from the tree if it exists Args: word str: word to be deleted Returns: bool: True if the word was found and deleted. False if word is not found RadixNodemyprefix.deletemystring False If there is remaining prefix, the word can't be on the tree We have word remaining so we check the next node If it is not a leaf, we don't have to delete We delete the nodes if no edges go from it We merge the current node with its only child If there is more than 1 edge, we just mark it as nonleaf If there is 1 edge, we merge it with its child Print the tree Args: height int, optional: Height of the printed node pytests
class RadixNode: def __init__(self, prefix: str = "", is_leaf: bool = False) -> None: # Mapping from the first character of the prefix of the node self.nodes: dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word self.is_leaf = is_leaf self.prefix = prefix def match(self, word: str) -> tuple[str, str, str]: """Compute the common substring of the prefix of the node and a word Args: word (str): word to compare Returns: (str, str, str): common substring, remaining prefix, remaining word >>> RadixNode("myprefix").match("mystring") ('my', 'prefix', 'string') """ x = 0 for q, w in zip(self.prefix, word): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def insert_many(self, words: list[str]) -> None: """Insert many words in the tree Args: words (list[str]): list of words >>> RadixNode("myprefix").insert_many(["mystring", "hello"]) """ for word in words: self.insert(word) def insert(self, word: str) -> None: """Insert a word into the tree Args: word (str): word to insert >>> RadixNode("myprefix").insert("mystring") >>> root = RadixNode() >>> root.insert_many(['myprefix', 'myprefixA', 'myprefixAA']) >>> root.print_tree() - myprefix (leaf) -- A (leaf) --- A (leaf) """ # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word and not self.is_leaf: self.is_leaf = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: self.nodes[word[0]] = RadixNode(prefix=word, is_leaf=True) else: incoming_node = self.nodes[word[0]] matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(remaining_word) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: incoming_node.prefix = remaining_prefix aux_node = self.nodes[matching_string[0]] self.nodes[matching_string[0]] = RadixNode(matching_string, False) self.nodes[matching_string[0]].nodes[remaining_prefix[0]] = aux_node if remaining_word == "": self.nodes[matching_string[0]].is_leaf = True else: self.nodes[matching_string[0]].insert(remaining_word) def find(self, word: str) -> bool: """Returns if the word is on the tree Args: word (str): word to check Returns: bool: True if the word appears on the tree >>> RadixNode("myprefix").find("mystring") False """ incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(remaining_word) def delete(self, word: str) -> bool: """Deletes a word from the tree if it exists Args: word (str): word to be deleted Returns: bool: True if the word was found and deleted. False if word is not found >>> RadixNode("myprefix").delete("mystring") False """ incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(remaining_word) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes) == 1 and not self.is_leaf: merging_node = next(iter(self.nodes.values())) self.is_leaf = merging_node.is_leaf self.prefix += merging_node.prefix self.nodes = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes) > 1: incoming_node.is_leaf = False # If there is 1 edge, we merge it with its child else: merging_node = next(iter(incoming_node.nodes.values())) incoming_node.is_leaf = merging_node.is_leaf incoming_node.prefix += merging_node.prefix incoming_node.nodes = merging_node.nodes return True def print_tree(self, height: int = 0) -> None: """Print the tree Args: height (int, optional): Height of the printed node """ if self.prefix != "": print("-" * height, self.prefix, " (leaf)" if self.is_leaf else "") for value in self.nodes.values(): value.print_tree(height + 1) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = RadixNode() root.insert_many(words) assert all(root.find(word) for word in words) assert not root.find("bandanas") assert not root.find("apps") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def pytests() -> None: assert test_trie() def main() -> None: """ >>> pytests() """ root = RadixNode() words = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(words) print("Words:", words) print("Tree:") root.print_tree() if __name__ == "__main__": main()
A TriePrefix Tree is a kind of search tree used to provide quick lookup of wordspatterns in a set of words. A basic Trie however has On2 space complexity making it impractical in practice. It however provides Omaxsearchstring, length of longest word lookup time making it an optimal approach when space is not an issue. Inserts a list of words into the Trie :param words: list of string words :return: None Inserts a word into the Trie :param word: word to be inserted :return: None Tries to find word in a Trie :param word: word to look for :return: Returns True if word is found, False otherwise Deletes a word in a Trie :param word: word to delete :return: None If word does not exist If char not in current trie node Flag to check if node can be deleted Prints all the words in a Trie :param node: root node of Trie :param word: Word variable should be empty at start :return: None printwordsroot, pytests
class TrieNode: def __init__(self) -> None: self.nodes: dict[str, TrieNode] = {} # Mapping from char to TrieNode self.is_leaf = False def insert_many(self, words: list[str]) -> None: """ Inserts a list of words into the Trie :param words: list of string words :return: None """ for word in words: self.insert(word) def insert(self, word: str) -> None: """ Inserts a word into the Trie :param word: word to be inserted :return: None """ curr = self for char in word: if char not in curr.nodes: curr.nodes[char] = TrieNode() curr = curr.nodes[char] curr.is_leaf = True def find(self, word: str) -> bool: """ Tries to find word in a Trie :param word: word to look for :return: Returns True if word is found, False otherwise """ curr = self for char in word: if char not in curr.nodes: return False curr = curr.nodes[char] return curr.is_leaf def delete(self, word: str) -> None: """ Deletes a word in a Trie :param word: word to delete :return: None """ def _delete(curr: TrieNode, word: str, index: int) -> bool: if index == len(word): # If word does not exist if not curr.is_leaf: return False curr.is_leaf = False return len(curr.nodes) == 0 char = word[index] char_node = curr.nodes.get(char) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted delete_curr = _delete(char_node, word, index + 1) if delete_curr: del curr.nodes[char] return len(curr.nodes) == 0 return delete_curr _delete(self, word, 0) def print_words(node: TrieNode, word: str) -> None: """ Prints all the words in a Trie :param node: root node of Trie :param word: Word variable should be empty at start :return: None """ if node.is_leaf: print(word, end=" ") for key, value in node.nodes.items(): print_words(value, word + key) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = TrieNode() root.insert_many(words) # print_words(root, "") assert all(root.find(word) for word in words) assert root.find("banana") assert not root.find("bandanas") assert not root.find("apps") assert root.find("apple") assert root.find("all") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_trie() def main() -> None: """ >>> pytests() """ print_results("Testing trie functionality", test_trie()) if __name__ == "__main__": main()
Change the brightness of a PIL Image to a given level. Fundamental TransformationOperation that'll be performed on every bit. Load image Change brightness to 100
from PIL import Image def change_brightness(img: Image, level: float) -> Image: """ Change the brightness of a PIL Image to a given level. """ def brightness(c: int) -> float: """ Fundamental Transformation/Operation that'll be performed on every bit. """ return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("level must be between -255.0 (black) and 255.0 (white)") return img.point(brightness) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change brightness to 100 brigt_img = change_brightness(img, 100) brigt_img.save("image_data/lena_brightness.png", format="png")
Changing contrast with PIL This algorithm is used in https:noivce.pythonanywhere.com Python web app. psfblack: True ruff : True Function to change contrast Fundamental TransformationOperation that'll be performed on every bit. Load image Change contrast to 170
from PIL import Image def change_contrast(img: Image, level: int) -> Image: """ Function to change contrast """ factor = (259 * (level + 255)) / (255 * (259 - level)) def contrast(c: int) -> int: """ Fundamental Transformation/Operation that'll be performed on every bit. """ return int(128 + factor * (c - 128)) return img.point(contrast) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change contrast to 170 cont_img = change_contrast(img, 170) cont_img.save("image_data/lena_high_contrast.png", format="png")
Implemented an algorithm using opencv to convert a colored image into its negative getting number of pixels in the image converting each pixel's color to its negative read original image convert to its negative show result image
from cv2 import destroyAllWindows, imread, imshow, waitKey def convert_to_negative(img): # getting number of pixels in the image pixel_h, pixel_v = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(pixel_h): for j in range(pixel_v): img[i][j] = [255, 255, 255] - img[i][j] return img if __name__ == "__main__": # read original image img = imread("image_data/lena.jpg", 1) # convert to its negative neg = convert_to_negative(img) # show result image imshow("negative of original image", img) waitKey(0) destroyAllWindows()
Implementation Burke's algorithm dithering Burke's algorithm is using for converting grayscale image to black and white version Source: Source: https:en.wikipedia.orgwikiDither Note: Best results are given with threshold 12 max greyscale value. This implementation get RGB image and converts it to greyscale in runtime. max greyscale value for FFFFFF error table size 4 columns and 1 row greater than input image because of lack of if statements Burkes.getgreyscale3, 4, 5 4.185 Burkes.getgreyscale0, 0, 0 0.0 Burkes.getgreyscale255, 255, 255 255.0 Formula from https:en.wikipedia.orgwikiHSLandHSV cf Lightness section, and Fig 13c. We use the first of four possible. Burkes error propagation is current pixel: 832 432 232 432 832 432 232 create Burke's instances with original images in greyscale
import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class Burkes: """ Burke's algorithm is using for converting grayscale image to black and white version Source: Source: https://en.wikipedia.org/wiki/Dither Note: * Best results are given with threshold= ~1/2 * max greyscale value. * This implementation get RGB image and converts it to greyscale in runtime. """ def __init__(self, input_img, threshold: int): self.min_threshold = 0 # max greyscale value for #FFFFFF self.max_threshold = int(self.get_greyscale(255, 255, 255)) if not self.min_threshold < threshold < self.max_threshold: msg = f"Factor value should be from 0 to {self.max_threshold}" raise ValueError(msg) self.input_img = input_img self.threshold = threshold self.width, self.height = self.input_img.shape[1], self.input_img.shape[0] # error table size (+4 columns and +1 row) greater than input image because of # lack of if statements self.error_table = [ [0 for _ in range(self.height + 4)] for __ in range(self.width + 1) ] self.output_img = np.ones((self.width, self.height, 3), np.uint8) * 255 @classmethod def get_greyscale(cls, blue: int, green: int, red: int) -> float: """ >>> Burkes.get_greyscale(3, 4, 5) 4.185 >>> Burkes.get_greyscale(0, 0, 0) 0.0 >>> Burkes.get_greyscale(255, 255, 255) 255.0 """ """ Formula from https://en.wikipedia.org/wiki/HSL_and_HSV cf Lightness section, and Fig 13c. We use the first of four possible. """ return 0.114 * blue + 0.587 * green + 0.299 * red def process(self) -> None: for y in range(self.height): for x in range(self.width): greyscale = int(self.get_greyscale(*self.input_img[y][x])) if self.threshold > greyscale + self.error_table[y][x]: self.output_img[y][x] = (0, 0, 0) current_error = greyscale + self.error_table[y][x] else: self.output_img[y][x] = (255, 255, 255) current_error = greyscale + self.error_table[y][x] - 255 """ Burkes error propagation (`*` is current pixel): * 8/32 4/32 2/32 4/32 8/32 4/32 2/32 """ self.error_table[y][x + 1] += int(8 / 32 * current_error) self.error_table[y][x + 2] += int(4 / 32 * current_error) self.error_table[y + 1][x] += int(8 / 32 * current_error) self.error_table[y + 1][x + 1] += int(4 / 32 * current_error) self.error_table[y + 1][x + 2] += int(2 / 32 * current_error) self.error_table[y + 1][x - 1] += int(4 / 32 * current_error) self.error_table[y + 1][x - 2] += int(2 / 32 * current_error) if __name__ == "__main__": # create Burke's instances with original images in greyscale burkes_instances = [ Burkes(imread("image_data/lena.jpg", 1), threshold) for threshold in (1, 126, 130, 140) ] for burkes in burkes_instances: burkes.process() for burkes in burkes_instances: imshow( f"Original image with dithering threshold: {burkes.threshold}", burkes.output_img, ) waitKey(0) destroyAllWindows()
Nonmaximum suppression. If the edge strength of the current pixel is the largest compared to the other pixels in the mask with the same direction, the value will be preserved. Otherwise, the value will be suppressed. HighLow threshold detection. If an edge pixels gradient value is higher than the high threshold value, it is marked as a strong edge pixel. If an edge pixels gradient value is smaller than the high threshold value and larger than the low threshold value, it is marked as a weak edge pixel. If an edge pixel's value is smaller than the low threshold value, it will be suppressed. Edge tracking. Usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while noise responses are unconnected. As long as there is one strong edge pixel that is involved in its 8connected neighborhood, that weak edge point can be identified as one that should be preserved. gaussianfilter get the gradient and degree by sobelfilter read original image in gray mode canny edge detection
import cv2 import numpy as np from digital_image_processing.filters.convolve import img_convolve from digital_image_processing.filters.sobel_filter import sobel_filter PI = 180 def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = ( 1 / (2 * np.pi * sigma) * np.exp(-(np.square(x) + np.square(y)) / (2 * np.square(sigma))) ) return g def suppress_non_maximum(image_shape, gradient_direction, sobel_grad): """ Non-maximum suppression. If the edge strength of the current pixel is the largest compared to the other pixels in the mask with the same direction, the value will be preserved. Otherwise, the value will be suppressed. """ destination = np.zeros(image_shape) for row in range(1, image_shape[0] - 1): for col in range(1, image_shape[1] - 1): direction = gradient_direction[row, col] if ( 0 <= direction < PI / 8 or 15 * PI / 8 <= direction <= 2 * PI or 7 * PI / 8 <= direction <= 9 * PI / 8 ): w = sobel_grad[row, col - 1] e = sobel_grad[row, col + 1] if sobel_grad[row, col] >= w and sobel_grad[row, col] >= e: destination[row, col] = sobel_grad[row, col] elif ( PI / 8 <= direction < 3 * PI / 8 or 9 * PI / 8 <= direction < 11 * PI / 8 ): sw = sobel_grad[row + 1, col - 1] ne = sobel_grad[row - 1, col + 1] if sobel_grad[row, col] >= sw and sobel_grad[row, col] >= ne: destination[row, col] = sobel_grad[row, col] elif ( 3 * PI / 8 <= direction < 5 * PI / 8 or 11 * PI / 8 <= direction < 13 * PI / 8 ): n = sobel_grad[row - 1, col] s = sobel_grad[row + 1, col] if sobel_grad[row, col] >= n and sobel_grad[row, col] >= s: destination[row, col] = sobel_grad[row, col] elif ( 5 * PI / 8 <= direction < 7 * PI / 8 or 13 * PI / 8 <= direction < 15 * PI / 8 ): nw = sobel_grad[row - 1, col - 1] se = sobel_grad[row + 1, col + 1] if sobel_grad[row, col] >= nw and sobel_grad[row, col] >= se: destination[row, col] = sobel_grad[row, col] return destination def detect_high_low_threshold( image_shape, destination, threshold_low, threshold_high, weak, strong ): """ High-Low threshold detection. If an edge pixel’s gradient value is higher than the high threshold value, it is marked as a strong edge pixel. If an edge pixel’s gradient value is smaller than the high threshold value and larger than the low threshold value, it is marked as a weak edge pixel. If an edge pixel's value is smaller than the low threshold value, it will be suppressed. """ for row in range(1, image_shape[0] - 1): for col in range(1, image_shape[1] - 1): if destination[row, col] >= threshold_high: destination[row, col] = strong elif destination[row, col] <= threshold_low: destination[row, col] = 0 else: destination[row, col] = weak def track_edge(image_shape, destination, weak, strong): """ Edge tracking. Usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while noise responses are unconnected. As long as there is one strong edge pixel that is involved in its 8-connected neighborhood, that weak edge point can be identified as one that should be preserved. """ for row in range(1, image_shape[0]): for col in range(1, image_shape[1]): if destination[row, col] == weak: if 255 in ( destination[row, col + 1], destination[row, col - 1], destination[row - 1, col], destination[row + 1, col], destination[row - 1, col - 1], destination[row + 1, col - 1], destination[row - 1, col + 1], destination[row + 1, col + 1], ): destination[row, col] = strong else: destination[row, col] = 0 def canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255): # gaussian_filter gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4)) # get the gradient and degree by sobel_filter sobel_grad, sobel_theta = sobel_filter(gaussian_out) gradient_direction = PI + np.rad2deg(sobel_theta) destination = suppress_non_maximum(image.shape, gradient_direction, sobel_grad) detect_high_low_threshold( image.shape, destination, threshold_low, threshold_high, weak, strong ) track_edge(image.shape, destination, weak, strong) return destination if __name__ == "__main__": # read original image in gray mode lena = cv2.imread(r"../image_data/lena.jpg", 0) # canny edge detection canny_destination = canny(lena) cv2.imshow("canny", canny_destination) cv2.waitKey(0)
Implementation of Bilateral filter Inputs: img: A 2d image with values in between 0 and 1 varS: variance in space dimension. varI: variance in Intensity. N: Kernel sizeMust be an odd number Output: img:A 2d zero padded image with values in between 0 and 1 For applying gaussian function for each element in matrix. Creates a gaussian kernel of given dimension.
import math import sys import cv2 import numpy as np def vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray: # For applying gaussian function for each element in matrix. sigma = math.sqrt(variance) cons = 1 / (sigma * math.sqrt(2 * math.pi)) return cons * np.exp(-((img / sigma) ** 2) * 0.5) def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray: half = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray: # Creates a gaussian kernel of given dimension. arr = np.zeros((kernel_size, kernel_size)) for i in range(kernel_size): for j in range(kernel_size): arr[i, j] = math.sqrt( abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2 ) return vec_gaussian(arr, spatial_variance) def bilateral_filter( img: np.ndarray, spatial_variance: float, intensity_variance: float, kernel_size: int, ) -> np.ndarray: img2 = np.zeros(img.shape) gauss_ker = get_gauss_kernel(kernel_size, spatial_variance) size_x, size_y = img.shape for i in range(kernel_size // 2, size_x - kernel_size // 2): for j in range(kernel_size // 2, size_y - kernel_size // 2): img_s = get_slice(img, i, j, kernel_size) img_i = img_s - img_s[kernel_size // 2, kernel_size // 2] img_ig = vec_gaussian(img_i, intensity_variance) weights = np.multiply(gauss_ker, img_ig) vals = np.multiply(img_s, weights) val = np.sum(vals) / np.sum(weights) img2[i, j] = val return img2 def parse_args(args: list) -> tuple: filename = args[1] if args[1:] else "../image_data/lena.jpg" spatial_variance = float(args[2]) if args[2:] else 1.0 intensity_variance = float(args[3]) if args[3:] else 1.0 if args[4:]: kernel_size = int(args[4]) kernel_size = kernel_size + abs(kernel_size % 2 - 1) else: kernel_size = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": filename, spatial_variance, intensity_variance, kernel_size = parse_args(sys.argv) img = cv2.imread(filename, 0) cv2.imshow("input image", img) out = img / 255 out = out.astype("float32") out = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) out = out * 255 out = np.uint8(out) cv2.imshow("output image", out) cv2.waitKey(0) cv2.destroyAllWindows()
Author : lightXu File : convolve.py Time : 201978 0008 16:13 Pads image with the edge values of array. im2col, turn the ksizeksize pixels into a row and np.vstack all rows turn the kernel into shapekk, 1 reshape and get the dst image read original image turn image in gray scale value Laplace operator
# @Author : lightXu # @File : convolve.py # @Time : 2019/7/8 0008 下午 16:13 from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): rows, cols = image.shape dst_height = cols - block_size[1] + 1 dst_width = rows - block_size[0] + 1 image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) row = 0 for i in range(dst_height): for j in range(dst_width): window = ravel(image[i : i + block_size[0], j : j + block_size[1]]) image_array[row, :] = window row += 1 return image_array def img_convolve(image, filter_kernel): height, width = image.shape[0], image.shape[1] k_size = filter_kernel.shape[0] pad_size = k_size // 2 # Pads image with the edge values of array. image_tmp = pad(image, pad_size, mode="edge") # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = im2col(image_tmp, (k_size, k_size)) # turn the kernel into shape(k*k, 1) kernel_array = ravel(filter_kernel) # reshape and get the dst image dst = dot(image_array, kernel_array).reshape(height, width) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Laplace operator Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) out = img_convolve(gray, Laplace_kernel).astype(uint8) imshow("Laplacian", out) waitKey(0)
Implementation of the Gaborfilter https:en.wikipedia.orgwikiGaborfilter :param ksize: The kernelsize of the convolutional filter ksize x ksize :param sigma: standard deviation of the gaussian bell curve :param theta: The orientation of the normal to the parallel stripes of Gabor function. :param lambd: Wavelength of the sinusoidal component. :param gamma: The spatial aspect ratio and specifies the ellipticity of the support of Gabor function. :param psi: The phase offset of the sinusoidal function. gaborfilterkernel3, 8, 0, 10, 0, 0.tolist 0.8027212023735046, 1.0, 0.8027212023735046, 0.8027212023735046, 1.0, 0.8027212023735046, 0.8027212023735046, 1.0, 0.8027212023735046 prepare kernel the kernel size have to be odd each value distance from center degree to radiant get kernel x get kernel y fill kernel read original image turn image in gray scale value Apply multiple Kernel to detect edges ksize 10 sigma 8 lambd 10 gamma 0 psi 0
# Implementation of the Gaborfilter # https://en.wikipedia.org/wiki/Gabor_filter import numpy as np from cv2 import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filter2D, imread, imshow, waitKey def gabor_filter_kernel( ksize: int, sigma: int, theta: int, lambd: int, gamma: int, psi: int ) -> np.ndarray: """ :param ksize: The kernelsize of the convolutional filter (ksize x ksize) :param sigma: standard deviation of the gaussian bell curve :param theta: The orientation of the normal to the parallel stripes of Gabor function. :param lambd: Wavelength of the sinusoidal component. :param gamma: The spatial aspect ratio and specifies the ellipticity of the support of Gabor function. :param psi: The phase offset of the sinusoidal function. >>> gabor_filter_kernel(3, 8, 0, 10, 0, 0).tolist() [[0.8027212023735046, 1.0, 0.8027212023735046], [0.8027212023735046, 1.0, \ 0.8027212023735046], [0.8027212023735046, 1.0, 0.8027212023735046]] """ # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: ksize = ksize + 1 gabor = np.zeros((ksize, ksize), dtype=np.float32) # each value for y in range(ksize): for x in range(ksize): # distance from center px = x - ksize // 2 py = y - ksize // 2 # degree to radiant _theta = theta / 180 * np.pi cos_theta = np.cos(_theta) sin_theta = np.sin(_theta) # get kernel x _x = cos_theta * px + sin_theta * py # get kernel y _y = -sin_theta * px + cos_theta * py # fill kernel gabor[y, x] = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges out = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: """ ksize = 10 sigma = 8 lambd = 10 gamma = 0 psi = 0 """ kernel_10 = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filter2D(gray, CV_8UC3, kernel_10) out = out / out.max() * 255 out = out.astype(np.uint8) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
Implementation of gaussian filter algorithm dst image height and width im2col, turn the ksizeksize pixels into a row and np.vstack all rows turn the kernel into shapekk, 1 reshape and get the dst image read original image turn image in gray scale value get values with two different mask size show result images
from itertools import product from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uint8, zeros def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = 1 / (2 * pi * sigma) * exp(-(square(x) + square(y)) / (2 * square(sigma))) return g def gaussian_filter(image, k_size, sigma): height, width = image.shape[0], image.shape[1] # dst image height and width dst_height = height - k_size + 1 dst_width = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = zeros((dst_height * dst_width, k_size * k_size)) row = 0 for i, j in product(range(dst_height), range(dst_width)): window = ravel(image[i : i + k_size, j : j + k_size]) image_array[row, :] = window row += 1 # turn the kernel into shape(k*k, 1) gaussian_kernel = gen_gaussian_kernel(k_size, sigma) filter_array = ravel(gaussian_kernel) # reshape and get the dst image dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size gaussian3x3 = gaussian_filter(gray, 3, sigma=1) gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow("gaussian filter with 3x3 mask", gaussian3x3) imshow("gaussian filter with 5x5 mask", gaussian5x5) waitKey()
Author : ojaswani File : laplacianfilter.py Date : 10042023 :param src: the source image, which should be a grayscale or color image. :param ksize: the size of the kernel used to compute the Laplacian filter, which can be 1, 3, 5, or 7. mylaplaciansrcnp.array, ksize0 Traceback most recent call last: ... ValueError: ksize must be in 1, 3, 5, 7 Apply the Laplacian kernel using convolution read original image turn image in gray scale value Applying gaussian filter Apply multiple Kernel to detect edges
# @Author : ojas-wani # @File : laplacian_filter.py # @Date : 10/04/2023 import numpy as np from cv2 import ( BORDER_DEFAULT, COLOR_BGR2GRAY, CV_64F, cvtColor, filter2D, imread, imshow, waitKey, ) from digital_image_processing.filters.gaussian_filter import gaussian_filter def my_laplacian(src: np.ndarray, ksize: int) -> np.ndarray: """ :param src: the source image, which should be a grayscale or color image. :param ksize: the size of the kernel used to compute the Laplacian filter, which can be 1, 3, 5, or 7. >>> my_laplacian(src=np.array([]), ksize=0) Traceback (most recent call last): ... ValueError: ksize must be in (1, 3, 5, 7) """ kernels = { 1: np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]), 3: np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]), 5: np.array( [ [0, 0, -1, 0, 0], [0, -1, -2, -1, 0], [-1, -2, 16, -2, -1], [0, -1, -2, -1, 0], [0, 0, -1, 0, 0], ] ), 7: np.array( [ [0, 0, 0, -1, 0, 0, 0], [0, 0, -2, -3, -2, 0, 0], [0, -2, -7, -10, -7, -2, 0], [-1, -3, -10, 68, -10, -3, -1], [0, -2, -7, -10, -7, -2, 0], [0, 0, -2, -3, -2, 0, 0], [0, 0, 0, -1, 0, 0, 0], ] ), } if ksize not in kernels: msg = f"ksize must be in {tuple(kernels)}" raise ValueError(msg) # Apply the Laplacian kernel using convolution return filter2D( src, CV_64F, kernels[ksize], 0, borderType=BORDER_DEFAULT, anchor=(0, 0) ) if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Applying gaussian filter blur_image = gaussian_filter(gray, 3, sigma=1) # Apply multiple Kernel to detect edges laplacian_image = my_laplacian(ksize=3, src=blur_image) imshow("Original image", img) imshow("Detected edges using laplacian filter", laplacian_image) waitKey(0)
Comparing local neighborhood pixel value with threshold value of centre pixel. Exception is required when neighborhood value of a center pixel value is null. i.e. values present at boundaries. :param image: The image we're working with :param xcoordinate: xcoordinate of the pixel :param ycoordinate: The y coordinate of the pixel :param center: center pixel value :return: The value of the pixel is being returned. It takes an image, an x and y coordinate, and returns the decimal value of the local binary patternof the pixel at that coordinate :param image: the image to be processed :param xcoordinate: x coordinate of the pixel :param ycoordinate: the y coordinate of the pixel :return: The decimal value of the binary value of the pixels around the center pixel. skip getneighborspixel if center is null Starting from the top right, assigning value to pixels clockwise Converting the binary value to decimal. Reading the image and converting it to grayscale. Create a numpy array as the same height and width of read image Iterating through the image and calculating the local binary pattern value for each pixel.
import cv2 import numpy as np def get_neighbors_pixel( image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int ) -> int: """ Comparing local neighborhood pixel value with threshold value of centre pixel. Exception is required when neighborhood value of a center pixel value is null. i.e. values present at boundaries. :param image: The image we're working with :param x_coordinate: x-coordinate of the pixel :param y_coordinate: The y coordinate of the pixel :param center: center pixel value :return: The value of the pixel is being returned. """ try: return int(image[x_coordinate][y_coordinate] >= center) except (IndexError, TypeError): return 0 def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int) -> int: """ It takes an image, an x and y coordinate, and returns the decimal value of the local binary patternof the pixel at that coordinate :param image: the image to be processed :param x_coordinate: x coordinate of the pixel :param y_coordinate: the y coordinate of the pixel :return: The decimal value of the binary value of the pixels around the center pixel. """ center = image[x_coordinate][y_coordinate] powers = [1, 2, 4, 8, 16, 32, 64, 128] # skip get_neighbors_pixel if center is null if center is None: return 0 # Starting from the top right, assigning value to pixels clockwise binary_values = [ get_neighbors_pixel(image, x_coordinate - 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate - 1, center), ] # Converting the binary value to decimal. return sum( binary_value * power for binary_value, power in zip(binary_values, powers) ) if __name__ == "__main__": # Reading the image and converting it to grayscale. image = cv2.imread( "digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE ) # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the # local binary pattern value for each pixel. for i in range(image.shape[0]): for j in range(image.shape[1]): lbp_image[i][j] = local_binary_value(image, i, j) cv2.imshow("local binary pattern", lbp_image) cv2.waitKey(0) cv2.destroyAllWindows()
Implementation of median filter algorithm :param grayimg: gray image :param mask: mask size :return: image with median filter set image borders copy image size get mask according with mask calculate mask median read original image turn image in gray scale value get values with two different mask size show result images
from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): """ :param gray_img: gray image :param mask: mask size :return: image with median filter """ # set image borders bd = int(mask / 2) # copy image size median_img = zeros_like(gray_img) for i in range(bd, gray_img.shape[0] - bd): for j in range(bd, gray_img.shape[1] - bd): # get mask according with mask kernel = ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1]) # calculate mask median median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)] median_img[i, j] = median return median_img if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size median3x3 = median_filter(gray, 3) median5x5 = median_filter(gray, 5) # show result images imshow("median filter with 3x3 mask", median3x3) imshow("median filter with 5x5 mask", median5x5) waitKey(0)
Author : lightXu File : sobelfilter.py Time : 201978 0008 16:26 modify the pix within 0, 255 read original image turn image in gray scale value show result images
# @Author : lightXu # @File : sobel_filter.py # @Time : 2019/7/8 0008 下午 16:26 import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from digital_image_processing.filters.convolve import img_convolve def sobel_filter(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) dst_x = np.abs(img_convolve(image, kernel_x)) dst_y = np.abs(img_convolve(image, kernel_y)) # modify the pix within [0, 255] dst_x = dst_x * 255 / np.max(dst_x) dst_y = dst_y * 255 / np.max(dst_y) dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y))) dst_xy = dst_xy * 255 / np.max(dst_xy) dst = dst_xy.astype(np.uint8) theta = np.arctan2(dst_y, dst_x) return dst, theta if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) sobel_grad, sobel_theta = sobel_filter(gray) # show result images imshow("sobel filter", sobel_grad) imshow("sobel theta", sobel_theta) waitKey(0)
Created on Fri Sep 28 15:22:29 2018 author: Binish125
import copy import os import cv2 import numpy as np from matplotlib import pyplot as plt class ConstantStretch: def __init__(self): self.img = "" self.original_image = "" self.last_list = [] self.rem = 0 self.L = 256 self.sk = 0 self.k = 0 self.number_of_rows = 0 self.number_of_cols = 0 def stretch(self, input_image): self.img = cv2.imread(input_image, 0) self.original_image = copy.deepcopy(self.img) x, _, _ = plt.hist(self.img.ravel(), 256, [0, 256], label="x") self.k = np.sum(x) for i in range(len(x)): prk = x[i] / self.k self.sk += prk last = (self.L - 1) * self.sk if self.rem != 0: self.rem = int(last % last) last = int(last + 1 if self.rem >= 0.5 else last) self.last_list.append(last) self.number_of_rows = int(np.ma.count(self.img) / self.img[1].size) self.number_of_cols = self.img[1].size for i in range(self.number_of_cols): for j in range(self.number_of_rows): num = self.img[j][i] if num != self.last_list[num]: self.img[j][i] = self.last_list[num] cv2.imwrite("output_data/output.jpg", self.img) def plot_histogram(self): plt.hist(self.img.ravel(), 256, [0, 256]) def show_image(self): cv2.imshow("Output-Image", self.img) cv2.imshow("Input-Image", self.original_image) cv2.waitKey(5000) cv2.destroyAllWindows() if __name__ == "__main__": file_path = os.path.join(os.path.basename(__file__), "image_data/input.jpg") stretcher = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
Author: Joo Gustavo A. Amorim Author email: joaogustavoamorimgmail.com Coding date: jan 2019 pythonblack: True Imports Class implemented to calculus the index Class Summary This algorithm consists in calculating vegetation indices, these indices can be used for precision agriculture for example or remote sensing. There are functions to define the data and to calculate the implemented indices. Vegetation index https:en.wikipedia.orgwikiVegetationIndex A Vegetation Index VI is a spectral transformation of two or more bands designed to enhance the contribution of vegetation properties and allow reliable spatial and temporal intercomparisons of terrestrial photosynthetic activity and canopy structural variations Information about channels Wavelength range for each nir nearinfrared https:www.malvernpanalytical.combrproductstechnologynearinfraredspectroscopy Wavelength Range 700 nm to 2500 nm Red Edge https:en.wikipedia.orgwikiRededge Wavelength Range 680 nm to 730 nm red https:en.wikipedia.orgwikiColor Wavelength Range 635 nm to 700 nm blue https:en.wikipedia.orgwikiColor Wavelength Range 450 nm to 490 nm green https:en.wikipedia.orgwikiColor Wavelength Range 520 nm to 560 nm Implemented index list abbreviationOfIndexName list of channels used ARVI2 red, nir CCCI red, redEdge, nir CVI red, green, nir GLI red, green, blue NDVI red, nir BNDVI blue, nir redEdgeNDVI red, redEdge GNDVI green, nir GBNDVI green, blue, nir GRNDVI red, green, nir RBNDVI red, blue, nir PNDVI red, green, blue, nir ATSAVI red, nir BWDRVI blue, nir CIgreen green, nir CIrededge redEdge, nir CI red, blue CTVI red, nir GDVI green, nir EVI red, blue, nir GEMI red, nir GOSAVI green, nir GSAVI green, nir Hue red, green, blue IVI red, nir IPVI red, nir I red, green, blue RVI red, nir MRVI red, nir MSAVI red, nir NormG red, green, nir NormNIR red, green, nir NormR red, green, nir NGRDI red, green RI red, green S red, green, blue IF red, green, blue DVI red, nir TVI red, nir NDRE redEdge, nir list of all index implemented allIndex ARVI2, CCCI, CVI, GLI, NDVI, BNDVI, redEdgeNDVI, GNDVI, GBNDVI, GRNDVI, RBNDVI, PNDVI, ATSAVI, BWDRVI, CIgreen, CIrededge, CI, CTVI, GDVI, EVI, GEMI, GOSAVI, GSAVI, Hue, IVI, IPVI, I, RVI, MRVI, MSAVI, NormG, NormNIR, NormR, NGRDI, RI, S, IF, DVI, TVI, NDRE list of index with not blue channel notBlueIndex ARVI2, CCCI, CVI, NDVI, redEdgeNDVI, GNDVI, GRNDVI, ATSAVI, CIgreen, CIrededge, CTVI, GDVI, GEMI, GOSAVI, GSAVI, IVI, IPVI, RVI, MRVI, MSAVI, NormG, NormNIR, NormR, NGRDI, RI, DVI, TVI, NDRE list of index just with RGB channels RGBIndex GLI, CI, Hue, I, NGRDI, RI, S, IF performs the calculation of the index with the values instantiated in the class :str index: abbreviation of index name to perform Atmospherically Resistant Vegetation Index 2 https:www.indexdatabase.dedbisingle.php?id396 :return: index 0.181.17self.nirself.redself.nirself.red Canopy Chlorophyll Content Index https:www.indexdatabase.dedbisingle.php?id224 :return: index Chlorophyll vegetation index https:www.indexdatabase.dedbisingle.php?id391 :return: index self.green leaf index https:www.indexdatabase.dedbisingle.php?id375 :return: index Normalized Difference self.nirself.red Normalized Difference Vegetation Index, Calibrated NDVI CDVI https:www.indexdatabase.dedbisingle.php?id58 :return: index Normalized Difference self.nirself.blue self.bluenormalized difference vegetation index https:www.indexdatabase.dedbisingle.php?id135 :return: index Normalized Difference self.rededgeself.red https:www.indexdatabase.dedbisingle.php?id235 :return: index Normalized Difference self.nirself.green self.green NDVI https:www.indexdatabase.dedbisingle.php?id401 :return: index self.greenself.blue NDVI https:www.indexdatabase.dedbisingle.php?id186 :return: index self.greenself.red NDVI https:www.indexdatabase.dedbisingle.php?id185 :return: index self.redself.blue NDVI https:www.indexdatabase.dedbisingle.php?id187 :return: index Pan NDVI https:www.indexdatabase.dedbisingle.php?id188 :return: index Adjusted transformed soiladjusted VI https:www.indexdatabase.dedbisingle.php?id209 :return: index self.bluewide dynamic range vegetation index https:www.indexdatabase.dedbisingle.php?id136 :return: index Chlorophyll Index self.green https:www.indexdatabase.dedbisingle.php?id128 :return: index Chlorophyll Index self.redEdge https:www.indexdatabase.dedbisingle.php?id131 :return: index Coloration Index https:www.indexdatabase.dedbisingle.php?id11 :return: index Corrected Transformed Vegetation Index https:www.indexdatabase.dedbisingle.php?id244 :return: index Difference self.nirself.green self.green Difference Vegetation Index https:www.indexdatabase.dedbisingle.php?id27 :return: index Enhanced Vegetation Index https:www.indexdatabase.dedbisingle.php?id16 :return: index Global Environment Monitoring Index https:www.indexdatabase.dedbisingle.php?id25 :return: index self.green Optimized Soil Adjusted Vegetation Index https:www.indexdatabase.dedbisingle.php?id29 mit Y 0,16 :return: index self.green Soil Adjusted Vegetation Index https:www.indexdatabase.dedbisingle.php?id31 mit N 0,5 :return: index Hue https:www.indexdatabase.dedbisingle.php?id34 :return: index Ideal vegetation index https:www.indexdatabase.dedbisingle.php?id276 bintercept of vegetation line asoil line slope :return: index Infraself.red percentage vegetation index https:www.indexdatabase.dedbisingle.php?id35 :return: index Intensity https:www.indexdatabase.dedbisingle.php?id36 :return: index RatioVegetationIndex http:www.seosproject.eumodulesremotesensingremotesensingc03s01p01.html :return: index Modified Normalized Difference Vegetation Index RVI https:www.indexdatabase.dedbisingle.php?id275 :return: index Modified Soil Adjusted Vegetation Index https:www.indexdatabase.dedbisingle.php?id44 :return: index Norm G https:www.indexdatabase.dedbisingle.php?id50 :return: index Norm self.nir https:www.indexdatabase.dedbisingle.php?id51 :return: index Norm R https:www.indexdatabase.dedbisingle.php?id52 :return: index Normalized Difference self.greenself.red Normalized self.green self.red difference index, Visible Atmospherically Resistant Indices self.green VIself.green https:www.indexdatabase.dedbisingle.php?id390 :return: index Normalized Difference self.redself.green self.redness Index https:www.indexdatabase.dedbisingle.php?id74 :return: index Saturation https:www.indexdatabase.dedbisingle.php?id77 :return: index Shape Index https:www.indexdatabase.dedbisingle.php?id79 :return: index Simple Ratio self.nirself.red Difference Vegetation Index, Vegetation Index Number VIN https:www.indexdatabase.dedbisingle.php?id12 :return: index Transformed Vegetation Index https:www.indexdatabase.dedbisingle.php?id98 :return: index genering a random matrices to test this class red np.ones1000,1000, 1,dtypefloat64 46787 green np.ones1000,1000, 1,dtypefloat64 23487 blue np.ones1000,1000, 1,dtypefloat64 14578 redEdge np.ones1000,1000, 1,dtypefloat64 51045 nir np.ones1000,1000, 1,dtypefloat64 52200 Examples of how to use the class instantiating the class cl IndexCalculation instantiating the class with the values cl indexCalculationredred, greengreen, blueblue, redEdgeredEdge, nirnir how set the values after instantiate the class cl, for update the data or when don't instantiating the class with the values cl.setMatricesredred, greengreen, blueblue, redEdgeredEdge, nirnir calculating the indices for the instantiated values in the class Note: the CCCI index can be changed to any index implemented in the class. indexValueform1 cl.calculationCCCI, redred, greengreen, blueblue, redEdgeredEdge, nirnir.astypenp.float64 indexValueform2 cl.CCCI calculating the index with the values directly you can set just the values preferred note: the calculation function performs the function setMatrices indexValueform3 cl.calculationCCCI, redred, greengreen, blueblue, redEdgeredEdge, nirnir.astypenp.float64 printForm 1: np.array2stringindexValueform1, precision20, separator', ', floatmode'maxprecequal' printForm 2: np.array2stringindexValueform2, precision20, separator', ', floatmode'maxprecequal' printForm 3: np.array2stringindexValueform3, precision20, separator', ', floatmode'maxprecequal' A list of examples results for different type of data at NDVI float16 0.31567383 NDVI red 50, nir 100 float32 0.31578946 NDVI red 50, nir 100 float64 0.3157894736842105 NDVI red 50, nir 100 longdouble 0.3157894736842105 NDVI red 50, nir 100
# Author: João Gustavo A. Amorim # Author email: joaogustavoamorim@gmail.com # Coding date: jan 2019 # python/black: True # Imports import numpy as np # Class implemented to calculus the index class IndexCalculation: """ # Class Summary This algorithm consists in calculating vegetation indices, these indices can be used for precision agriculture for example (or remote sensing). There are functions to define the data and to calculate the implemented indices. # Vegetation index https://en.wikipedia.org/wiki/Vegetation_Index A Vegetation Index (VI) is a spectral transformation of two or more bands designed to enhance the contribution of vegetation properties and allow reliable spatial and temporal inter-comparisons of terrestrial photosynthetic activity and canopy structural variations # Information about channels (Wavelength range for each) * nir - near-infrared https://www.malvernpanalytical.com/br/products/technology/near-infrared-spectroscopy Wavelength Range 700 nm to 2500 nm * Red Edge https://en.wikipedia.org/wiki/Red_edge Wavelength Range 680 nm to 730 nm * red https://en.wikipedia.org/wiki/Color Wavelength Range 635 nm to 700 nm * blue https://en.wikipedia.org/wiki/Color Wavelength Range 450 nm to 490 nm * green https://en.wikipedia.org/wiki/Color Wavelength Range 520 nm to 560 nm # Implemented index list #"abbreviationOfIndexName" -- list of channels used #"ARVI2" -- red, nir #"CCCI" -- red, redEdge, nir #"CVI" -- red, green, nir #"GLI" -- red, green, blue #"NDVI" -- red, nir #"BNDVI" -- blue, nir #"redEdgeNDVI" -- red, redEdge #"GNDVI" -- green, nir #"GBNDVI" -- green, blue, nir #"GRNDVI" -- red, green, nir #"RBNDVI" -- red, blue, nir #"PNDVI" -- red, green, blue, nir #"ATSAVI" -- red, nir #"BWDRVI" -- blue, nir #"CIgreen" -- green, nir #"CIrededge" -- redEdge, nir #"CI" -- red, blue #"CTVI" -- red, nir #"GDVI" -- green, nir #"EVI" -- red, blue, nir #"GEMI" -- red, nir #"GOSAVI" -- green, nir #"GSAVI" -- green, nir #"Hue" -- red, green, blue #"IVI" -- red, nir #"IPVI" -- red, nir #"I" -- red, green, blue #"RVI" -- red, nir #"MRVI" -- red, nir #"MSAVI" -- red, nir #"NormG" -- red, green, nir #"NormNIR" -- red, green, nir #"NormR" -- red, green, nir #"NGRDI" -- red, green #"RI" -- red, green #"S" -- red, green, blue #"IF" -- red, green, blue #"DVI" -- red, nir #"TVI" -- red, nir #"NDRE" -- redEdge, nir #list of all index implemented #allIndex = ["ARVI2", "CCCI", "CVI", "GLI", "NDVI", "BNDVI", "redEdgeNDVI", "GNDVI", "GBNDVI", "GRNDVI", "RBNDVI", "PNDVI", "ATSAVI", "BWDRVI", "CIgreen", "CIrededge", "CI", "CTVI", "GDVI", "EVI", "GEMI", "GOSAVI", "GSAVI", "Hue", "IVI", "IPVI", "I", "RVI", "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "S", "IF", "DVI", "TVI", "NDRE"] #list of index with not blue channel #notBlueIndex = ["ARVI2", "CCCI", "CVI", "NDVI", "redEdgeNDVI", "GNDVI", "GRNDVI", "ATSAVI", "CIgreen", "CIrededge", "CTVI", "GDVI", "GEMI", "GOSAVI", "GSAVI", "IVI", "IPVI", "RVI", "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "DVI", "TVI", "NDRE"] #list of index just with RGB channels #RGBIndex = ["GLI", "CI", "Hue", "I", "NGRDI", "RI", "S", "IF"] """ def __init__(self, red=None, green=None, blue=None, red_edge=None, nir=None): self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) def set_matricies(self, red=None, green=None, blue=None, red_edge=None, nir=None): if red is not None: self.red = red if green is not None: self.green = green if blue is not None: self.blue = blue if red_edge is not None: self.redEdge = red_edge if nir is not None: self.nir = nir return True def calculation( self, index="", red=None, green=None, blue=None, red_edge=None, nir=None ): """ performs the calculation of the index with the values instantiated in the class :str index: abbreviation of index name to perform """ self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) funcs = { "ARVI2": self.arv12, "CCCI": self.ccci, "CVI": self.cvi, "GLI": self.gli, "NDVI": self.ndvi, "BNDVI": self.bndvi, "redEdgeNDVI": self.red_edge_ndvi, "GNDVI": self.gndvi, "GBNDVI": self.gbndvi, "GRNDVI": self.grndvi, "RBNDVI": self.rbndvi, "PNDVI": self.pndvi, "ATSAVI": self.atsavi, "BWDRVI": self.bwdrvi, "CIgreen": self.ci_green, "CIrededge": self.ci_rededge, "CI": self.ci, "CTVI": self.ctvi, "GDVI": self.gdvi, "EVI": self.evi, "GEMI": self.gemi, "GOSAVI": self.gosavi, "GSAVI": self.gsavi, "Hue": self.hue, "IVI": self.ivi, "IPVI": self.ipvi, "I": self.i, "RVI": self.rvi, "MRVI": self.mrvi, "MSAVI": self.m_savi, "NormG": self.norm_g, "NormNIR": self.norm_nir, "NormR": self.norm_r, "NGRDI": self.ngrdi, "RI": self.ri, "S": self.s, "IF": self._if, "DVI": self.dvi, "TVI": self.tvi, "NDRE": self.ndre, } try: return funcs[index]() except KeyError: print("Index not in the list!") return False def arv12(self): """ Atmospherically Resistant Vegetation Index 2 https://www.indexdatabase.de/db/i-single.php?id=396 :return: index −0.18+1.17*(self.nir−self.red)/(self.nir+self.red) """ return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def ccci(self): """ Canopy Chlorophyll Content Index https://www.indexdatabase.de/db/i-single.php?id=224 :return: index """ return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def cvi(self): """ Chlorophyll vegetation index https://www.indexdatabase.de/db/i-single.php?id=391 :return: index """ return self.nir * (self.red / (self.green**2)) def gli(self): """ self.green leaf index https://www.indexdatabase.de/db/i-single.php?id=375 :return: index """ return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def ndvi(self): """ Normalized Difference self.nir/self.red Normalized Difference Vegetation Index, Calibrated NDVI - CDVI https://www.indexdatabase.de/db/i-single.php?id=58 :return: index """ return (self.nir - self.red) / (self.nir + self.red) def bndvi(self): """ Normalized Difference self.nir/self.blue self.blue-normalized difference vegetation index https://www.indexdatabase.de/db/i-single.php?id=135 :return: index """ return (self.nir - self.blue) / (self.nir + self.blue) def red_edge_ndvi(self): """ Normalized Difference self.rededge/self.red https://www.indexdatabase.de/db/i-single.php?id=235 :return: index """ return (self.redEdge - self.red) / (self.redEdge + self.red) def gndvi(self): """ Normalized Difference self.nir/self.green self.green NDVI https://www.indexdatabase.de/db/i-single.php?id=401 :return: index """ return (self.nir - self.green) / (self.nir + self.green) def gbndvi(self): """ self.green-self.blue NDVI https://www.indexdatabase.de/db/i-single.php?id=186 :return: index """ return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def grndvi(self): """ self.green-self.red NDVI https://www.indexdatabase.de/db/i-single.php?id=185 :return: index """ return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def rbndvi(self): """ self.red-self.blue NDVI https://www.indexdatabase.de/db/i-single.php?id=187 :return: index """ return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def pndvi(self): """ Pan NDVI https://www.indexdatabase.de/db/i-single.php?id=188 :return: index """ return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def atsavi(self, x=0.08, a=1.22, b=0.03): """ Adjusted transformed soil-adjusted VI https://www.indexdatabase.de/db/i-single.php?id=209 :return: index """ return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def bwdrvi(self): """ self.blue-wide dynamic range vegetation index https://www.indexdatabase.de/db/i-single.php?id=136 :return: index """ return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def ci_green(self): """ Chlorophyll Index self.green https://www.indexdatabase.de/db/i-single.php?id=128 :return: index """ return (self.nir / self.green) - 1 def ci_rededge(self): """ Chlorophyll Index self.redEdge https://www.indexdatabase.de/db/i-single.php?id=131 :return: index """ return (self.nir / self.redEdge) - 1 def ci(self): """ Coloration Index https://www.indexdatabase.de/db/i-single.php?id=11 :return: index """ return (self.red - self.blue) / self.red def ctvi(self): """ Corrected Transformed Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=244 :return: index """ ndvi = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2)) def gdvi(self): """ Difference self.nir/self.green self.green Difference Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=27 :return: index """ return self.nir - self.green def evi(self): """ Enhanced Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=16 :return: index """ return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def gemi(self): """ Global Environment Monitoring Index https://www.indexdatabase.de/db/i-single.php?id=25 :return: index """ n = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) def gosavi(self, y=0.16): """ self.green Optimized Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=29 mit Y = 0,16 :return: index """ return (self.nir - self.green) / (self.nir + self.green + y) def gsavi(self, n=0.5): """ self.green Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=31 mit N = 0,5 :return: index """ return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def hue(self): """ Hue https://www.indexdatabase.de/db/i-single.php?id=34 :return: index """ return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def ivi(self, a=None, b=None): """ Ideal vegetation index https://www.indexdatabase.de/db/i-single.php?id=276 b=intercept of vegetation line a=soil line slope :return: index """ return (self.nir - b) / (a * self.red) def ipvi(self): """ Infraself.red percentage vegetation index https://www.indexdatabase.de/db/i-single.php?id=35 :return: index """ return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def i(self): """ Intensity https://www.indexdatabase.de/db/i-single.php?id=36 :return: index """ return (self.red + self.green + self.blue) / 30.5 def rvi(self): """ Ratio-Vegetation-Index http://www.seos-project.eu/modules/remotesensing/remotesensing-c03-s01-p01.html :return: index """ return self.nir / self.red def mrvi(self): """ Modified Normalized Difference Vegetation Index RVI https://www.indexdatabase.de/db/i-single.php?id=275 :return: index """ return (self.rvi() - 1) / (self.rvi() + 1) def m_savi(self): """ Modified Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=44 :return: index """ return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def norm_g(self): """ Norm G https://www.indexdatabase.de/db/i-single.php?id=50 :return: index """ return self.green / (self.nir + self.red + self.green) def norm_nir(self): """ Norm self.nir https://www.indexdatabase.de/db/i-single.php?id=51 :return: index """ return self.nir / (self.nir + self.red + self.green) def norm_r(self): """ Norm R https://www.indexdatabase.de/db/i-single.php?id=52 :return: index """ return self.red / (self.nir + self.red + self.green) def ngrdi(self): """ Normalized Difference self.green/self.red Normalized self.green self.red difference index, Visible Atmospherically Resistant Indices self.green (VIself.green) https://www.indexdatabase.de/db/i-single.php?id=390 :return: index """ return (self.green - self.red) / (self.green + self.red) def ri(self): """ Normalized Difference self.red/self.green self.redness Index https://www.indexdatabase.de/db/i-single.php?id=74 :return: index """ return (self.red - self.green) / (self.red + self.green) def s(self): """ Saturation https://www.indexdatabase.de/db/i-single.php?id=77 :return: index """ max_value = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) min_value = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) return (max_value - min_value) / max_value def _if(self): """ Shape Index https://www.indexdatabase.de/db/i-single.php?id=79 :return: index """ return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def dvi(self): """ Simple Ratio self.nir/self.red Difference Vegetation Index, Vegetation Index Number (VIN) https://www.indexdatabase.de/db/i-single.php?id=12 :return: index """ return self.nir / self.red def tvi(self): """ Transformed Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=98 :return: index """ return (self.ndvi() + 0.5) ** (1 / 2) def ndre(self): return (self.nir - self.redEdge) / (self.nir + self.redEdge) """ # genering a random matrices to test this class red = np.ones((1000,1000, 1),dtype="float64") * 46787 green = np.ones((1000,1000, 1),dtype="float64") * 23487 blue = np.ones((1000,1000, 1),dtype="float64") * 14578 redEdge = np.ones((1000,1000, 1),dtype="float64") * 51045 nir = np.ones((1000,1000, 1),dtype="float64") * 52200 # Examples of how to use the class # instantiating the class cl = IndexCalculation() # instantiating the class with the values #cl = indexCalculation(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir) # how set the values after instantiate the class cl, (for update the data or when don't # instantiating the class with the values) cl.setMatrices(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir) # calculating the indices for the instantiated values in the class # Note: the CCCI index can be changed to any index implemented in the class. indexValue_form1 = cl.calculation("CCCI", red=red, green=green, blue=blue, redEdge=redEdge, nir=nir).astype(np.float64) indexValue_form2 = cl.CCCI() # calculating the index with the values directly -- you can set just the values # preferred note: the *calculation* function performs the function *setMatrices* indexValue_form3 = cl.calculation("CCCI", red=red, green=green, blue=blue, redEdge=redEdge, nir=nir).astype(np.float64) print("Form 1: "+np.array2string(indexValue_form1, precision=20, separator=', ', floatmode='maxprec_equal')) print("Form 2: "+np.array2string(indexValue_form2, precision=20, separator=', ', floatmode='maxprec_equal')) print("Form 3: "+np.array2string(indexValue_form3, precision=20, separator=', ', floatmode='maxprec_equal')) # A list of examples results for different type of data at NDVI # float16 -> 0.31567383 #NDVI (red = 50, nir = 100) # float32 -> 0.31578946 #NDVI (red = 50, nir = 100) # float64 -> 0.3157894736842105 #NDVI (red = 50, nir = 100) # longdouble -> 0.3157894736842105 #NDVI (red = 50, nir = 100) """
Return gray image from rgb image rgbtograynp.array127, 255, 0 array187.6453 rgbtograynp.array0, 0, 0 array0. rgbtograynp.array2, 4, 1 array3.0598 rgbtograynp.array26, 255, 14, 5, 147, 20, 1, 200, 0 array159.0524, 90.0635, 117.6989 Return binary image from gray image graytobinarynp.array127, 255, 0 arrayFalse, True, False graytobinarynp.array0 arrayFalse graytobinarynp.array26.2409, 4.9315, 1.4729 arrayFalse, False, False graytobinarynp.array26, 255, 14, 5, 147, 20, 1, 200, 0 arrayFalse, True, False, False, True, False, False, True, False Return dilated image dilationnp.arrayTrue, False, True, np.array0, 1, 0 arrayFalse, False, False dilationnp.arrayFalse, False, True, np.array1, 0, 1 arrayFalse, False, False Copy image to padded image Iterate over image apply kernel read original image kernel to be applied Save the output image
from pathlib import Path import numpy as np from PIL import Image def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: """ Return gray image from rgb image >>> rgb_to_gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb_to_gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb_to_gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb_to_gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray_to_binary(gray: np.ndarray) -> np.ndarray: """ Return binary image from gray image >>> gray_to_binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray_to_binary(np.array([[0]])) array([[False]]) >>> gray_to_binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray_to_binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (gray > 127) & (gray <= 255) def dilation(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: """ Return dilated image >>> dilation(np.array([[True, False, True]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> dilation(np.array([[False, False, True]]), np.array([[1, 0, 1]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation > 0) return output if __name__ == "__main__": # read original image lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" lena = np.array(Image.open(lena_path)) # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) output = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
Return gray image from rgb image rgbtograynp.array127, 255, 0 array187.6453 rgbtograynp.array0, 0, 0 array0. rgbtograynp.array2, 4, 1 array3.0598 rgbtograynp.array26, 255, 14, 5, 147, 20, 1, 200, 0 array159.0524, 90.0635, 117.6989 Return binary image from gray image graytobinarynp.array127, 255, 0 arrayFalse, True, False graytobinarynp.array0 arrayFalse graytobinarynp.array26.2409, 4.9315, 1.4729 arrayFalse, False, False graytobinarynp.array26, 255, 14, 5, 147, 20, 1, 200, 0 arrayFalse, True, False, False, True, False, False, True, False Return eroded image erosionnp.arrayTrue, True, False, np.array0, 1, 0 arrayFalse, False, False erosionnp.arrayTrue, False, False, np.array1, 1, 0 arrayFalse, False, False Copy image to padded image Iterate over image apply kernel read original image kernel to be applied Apply erosion operation to a binary image Save the output image
from pathlib import Path import numpy as np from PIL import Image def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: """ Return gray image from rgb image >>> rgb_to_gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb_to_gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb_to_gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb_to_gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray_to_binary(gray: np.ndarray) -> np.ndarray: """ Return binary image from gray image >>> gray_to_binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray_to_binary(np.array([[0]])) array([[False]]) >>> gray_to_binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray_to_binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (gray > 127) & (gray <= 255) def erosion(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: """ Return eroded image >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output if __name__ == "__main__": # read original image lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" lena = np.array(Image.open(lena_path)) # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) # Apply erosion operation to a binary image output = erosion(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
Multiple image resizing techniques import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: def initself, img, dstwidth: int, dstheight: int: if dstwidth 0 or dstheight 0: raise ValueErrorDestination widthheight should be 0 self.img img self.srcw img.shape1 self.srch img.shape0 self.dstw dstwidth self.dsth dstheight self.ratiox self.srcw self.dstw self.ratioy self.srch self.dsth self.output self.outputimg np.onesself.dsth, self.dstw, 3, np.uint8 255 def processself: for i in rangeself.dsth: for j in rangeself.dstw: self.outputij self.imgself.getyiself.getxj def getxself, x: int int: return intself.ratiox x def getyself, y: int int: return intself.ratioy y if name main: dstw, dsth 800, 600 im imreadimagedatalena.jpg, 1 n NearestNeighbourim, dstw, dsth n.process imshow fImage resized from: im.shape1xim.shape0 to dstwxdsth, n.output waitKey0 destroyAllWindows
import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: """ Simplest and fastest version of image resizing. Source: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation """ def __init__(self, img, dst_width: int, dst_height: int): if dst_width < 0 or dst_height < 0: raise ValueError("Destination width/height should be > 0") self.img = img self.src_w = img.shape[1] self.src_h = img.shape[0] self.dst_w = dst_width self.dst_h = dst_height self.ratio_x = self.src_w / self.dst_w self.ratio_y = self.src_h / self.dst_h self.output = self.output_img = ( np.ones((self.dst_h, self.dst_w, 3), np.uint8) * 255 ) def process(self): for i in range(self.dst_h): for j in range(self.dst_w): self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)] def get_x(self, x: int) -> int: """ Get parent X coordinate for destination X :param x: Destination X coordinate :return: Parent X coordinate based on `x ratio` >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", ... 1), 100, 100) >>> nn.ratio_x = 0.5 >>> nn.get_x(4) 2 """ return int(self.ratio_x * x) def get_y(self, y: int) -> int: """ Get parent Y coordinate for destination Y :param y: Destination X coordinate :return: Parent X coordinate based on `y ratio` >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", ... 1), 100, 100) >>> nn.ratio_y = 0.5 >>> nn.get_y(4) 2 """ return int(self.ratio_y * y) if __name__ == "__main__": dst_w, dst_h = 800, 600 im = imread("image_data/lena.jpg", 1) n = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
Get image rotation :param img: np.ndarray :param pt1: 3x2 list :param pt2: 3x2 list :param rows: columns image shape :param cols: rows image shape :return: np.ndarray read original image turn image in gray scale value get image shape set different points to rotate image add all rotated images in a list plot different image rotations
from pathlib import Path import cv2 import numpy as np from matplotlib import pyplot as plt def get_rotation( img: np.ndarray, pt1: np.ndarray, pt2: np.ndarray, rows: int, cols: int ) -> np.ndarray: """ Get image rotation :param img: np.ndarray :param pt1: 3x2 list :param pt2: 3x2 list :param rows: columns image shape :param cols: rows image shape :return: np.ndarray """ matrix = cv2.getAffineTransform(pt1, pt2) return cv2.warpAffine(img, matrix, (rows, cols)) if __name__ == "__main__": # read original image image = cv2.imread( str(Path(__file__).resolve().parent.parent / "image_data" / "lena.jpg") ) # turn image in gray scale value gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # get image shape img_rows, img_cols = gray_img.shape # set different points to rotate image pts1 = np.array([[50, 50], [200, 50], [50, 200]], np.float32) pts2 = np.array([[10, 100], [200, 50], [100, 250]], np.float32) pts3 = np.array([[50, 50], [150, 50], [120, 200]], np.float32) pts4 = np.array([[10, 100], [80, 50], [180, 250]], np.float32) # add all rotated images in a list images = [ gray_img, get_rotation(gray_img, pts1, pts2, img_rows, img_cols), get_rotation(gray_img, pts2, pts3, img_rows, img_cols), get_rotation(gray_img, pts2, pts4, img_rows, img_cols), ] # plot different image rotations fig = plt.figure(1) titles = ["Original", "Rotation 1", "Rotation 2", "Rotation 3"] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, "gray") plt.title(titles[i]) plt.axis("off") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
Implemented an algorithm using opencv to tone an image with sepia technique Function create sepia tone. Source: https:en.wikipedia.orgwikiSepiacolor Helper function to create pixel's greyscale representation Src: https:pl.wikipedia.orgwikiYUV Helper function to normalize RGB value return 255 if value 255 return minvalue, 255 for i in rangepixelh: for j in rangepixelv: greyscale inttograyscaleimgij imgij normalizegreyscale, normalizegreyscale factor, normalizegreyscale 2 factor, return img if name main: read original image images percentage: imreadimagedatalena.jpg, 1 for percentage in 10, 20, 30, 40 for percentage, img in images.items: makesepiaimg, percentage for percentage, img in images.items: imshowfOriginal image with sepia factor: percentage, img waitKey0 destroyAllWindows
from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): """ Function create sepia tone. Source: https://en.wikipedia.org/wiki/Sepia_(color) """ pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): """ Helper function to create pixel's greyscale representation Src: https://pl.wikipedia.org/wiki/YUV """ return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): """Helper function to normalize R/G/B value -> return 255 if value > 255""" return min(value, 255) for i in range(pixel_h): for j in range(pixel_v): greyscale = int(to_grayscale(*img[i][j])) img[i][j] = [ normalize(greyscale), normalize(greyscale + factor), normalize(greyscale + 2 * factor), ] return img if __name__ == "__main__": # read original image images = { percentage: imread("image_data/lena.jpg", 1) for percentage in (10, 20, 30, 40) } for percentage, img in images.items(): make_sepia(img, percentage) for percentage, img in images.items(): imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) destroyAllWindows()
PyTest's for Digital Image Processing Test: converttonegative assert negativeimg array for at least one True Test: changecontrast Work around assertion for response canny.gengaussiankernel Assert ambiguous array canny.py assert ambiguous array for all True assert canny array for at least one True filtersgaussianfilter.py laplace diagonals pull request 10161 before: digitalimageprocessingimagedatalena.jpg after: digitalimageprocessingimagedatalenasmall.jpg Reading the image and converting it to grayscale Test for getneighborspixel function return not None Test for localbinarypattern function Create a numpy array as the same height and width of read image Iterating through the image and calculating the local binary pattern value for each pixel.
import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uint8 from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs img = imread(r"digital_image_processing/image_data/lena_small.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) # Test: convert_to_negative() def test_convert_to_negative(): negative_img = cn.convert_to_negative(img) # assert negative_img array for at least one True assert negative_img.any() # Test: change_contrast() def test_change_contrast(): with Image.open("digital_image_processing/image_data/lena_small.jpg") as img: # Work around assertion for response assert str(cc.change_contrast(img, 110)).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) # canny.gen_gaussian_kernel() def test_gen_gaussian_kernel(): resp = canny.gen_gaussian_kernel(9, sigma=1.4) # Assert ambiguous array assert resp.all() # canny.py def test_canny(): canny_img = imread("digital_image_processing/image_data/lena_small.jpg", 0) # assert ambiguous array for all == True assert canny_img.all() canny_array = canny.canny(canny_img) # assert canny array for at least one True assert canny_array.any() # filters/gaussian_filter.py def test_gen_gaussian_kernel_filter(): assert gg.gaussian_filter(gray, 5, sigma=0.9).all() def test_convolve_filter(): # laplace diagonals laplace = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]) res = conv.img_convolve(gray, laplace).astype(uint8) assert res.any() def test_median_filter(): assert med.median_filter(gray, 3).any() def test_sobel_filter(): grad, theta = sob.sobel_filter(gray) assert grad.any() assert theta.any() def test_sepia(): sepia = sp.make_sepia(img, 20) assert sepia.all() def test_burkes(file_path: str = "digital_image_processing/image_data/lena_small.jpg"): burkes = bs.Burkes(imread(file_path, 1), 120) burkes.process() assert burkes.output_img.any() def test_nearest_neighbour( file_path: str = "digital_image_processing/image_data/lena_small.jpg", ): nn = rs.NearestNeighbour(imread(file_path, 1), 400, 200) nn.process() assert nn.output.any() def test_local_binary_pattern(): # pull request 10161 before: # "digital_image_processing/image_data/lena.jpg" # after: "digital_image_processing/image_data/lena_small.jpg" from os import getenv # Speed up our Continuous Integration tests file_name = "lena_small.jpg" if getenv("CI") else "lena.jpg" file_path = f"digital_image_processing/image_data/{file_name}" # Reading the image and converting it to grayscale image = imread(file_path, 0) # Test for get_neighbors_pixel function() return not None x_coordinate = 0 y_coordinate = 0 center = image[x_coordinate][y_coordinate] neighbors_pixels = lbp.get_neighbors_pixel( image, x_coordinate, y_coordinate, center ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(image.shape[0]): for j in range(image.shape[1]): lbp_image[i][j] = lbp.local_binary_value(image, i, j) assert lbp_image.any()
The algorithm finds distance between closest pair of points in the given n points. Approach used Divide and conquer The points are sorted based on Xcoords and then based on Ycoords separately. And by applying divide and conquer approach, minimum distance is obtained recursively. Closest points can lie on different sides of partition. This case handled by forming a strip of points whose Xcoords distance is less than closestpairdis from midpoint's Xcoords. Points sorted based on Ycoords are used in this step to reduce sorting time. Closest pair distance is found in the strip of points. closestinstrip minclosestpairdis, closestinstrip would be the final answer. Time complexity: On log n euclideandistancesqr1,2,2,4 5 columnbasedsort5, 1, 4, 2, 3, 0, 1 3, 0, 5, 1, 4, 2 brute force approach to find distance between closest pair points Parameters : points, pointscount, mindis listtupleint, int, int, int Returns : mindis float: distance between closest pair of points disbetweenclosestpair1,2,2,4,5,7,8,9,11,0,5 5 closest pair of points in strip Parameters : points, pointscount, mindis listtupleint, int, int, int Returns : mindis float: distance btw closest pair of points in the strip mindis disbetweenclosestinstrip1,2,2,4,5,7,8,9,11,0,5 85 divide and conquer approach Parameters : points, pointscount listtupleint, int, int Returns : float: distance btw closest pair of points closestpairofpointssqr1, 2, 3, 4, 5, 6, 7, 8, 2 8 base case recursion crossstrip contains the points, whose Xcoords are at a distance closestpairdis from mid's Xcoord closestpairofpoints2, 3, 12, 30, len2, 3, 12, 30 28.792360097775937
def euclidean_distance_sqr(point1, point2): """ >>> euclidean_distance_sqr([1,2],[2,4]) 5 """ return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column=0): """ >>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1) [(3, 0), (5, 1), (4, 2)] """ return sorted(array, key=lambda x: x[column]) def dis_between_closest_pair(points, points_counts, min_dis=float("inf")): """ brute force approach to find distance between closest pair points Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance between closest pair of points >>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 5 """ for i in range(points_counts - 1): for j in range(i + 1, points_counts): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): """ closest pair of points in strip Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance btw closest pair of points in the strip (< min_dis) >>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 85 """ for i in range(min(6, points_counts - 1), points_counts): for j in range(max(0, i - 6), i): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): """divide and conquer approach Parameters : points, points_count (list(tuple(int, int)), int) Returns : (float): distance btw closest pair of points >>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2) 8 """ # base case if points_counts <= 3: return dis_between_closest_pair(points_sorted_on_x, points_counts) # recursion mid = points_counts // 2 closest_in_left = closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y[:mid], mid ) closest_in_right = closest_pair_of_points_sqr( points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid ) closest_pair_dis = min(closest_in_left, closest_in_right) """ cross_strip contains the points, whose Xcoords are at a distance(< closest_pair_dis) from mid's Xcoord """ cross_strip = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis: cross_strip.append(point) closest_in_strip = dis_between_closest_in_strip( cross_strip, len(cross_strip), closest_pair_dis ) return min(closest_pair_dis, closest_in_strip) def closest_pair_of_points(points, points_counts): """ >>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)])) 28.792360097775937 """ points_sorted_on_x = column_based_sort(points, column=0) points_sorted_on_y = column_based_sort(points, column=1) return ( closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y, points_counts ) ) ** 0.5 if __name__ == "__main__": points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
The convex hull problem is problem of finding all the vertices of convex polygon, P of a set of points in a plane such that all the points are either on the vertices of P or inside P. TH convex hull problem has several applications in geometrical problems, computer graphics and game development. Two algorithms have been implemented for the convex hull problem here. 1. A bruteforce algorithm which runs in On3 2. A divideandconquer algorithm which runs in On logn There are other several other algorithms for the convex hull problem which have not been implemented here, yet. Defines a 2d point for use by all convexhull algorithms. Parameters x: an int or a float, the xcoordinate of the 2d point y: an int or a float, the ycoordinate of the 2d point Examples Point1, 2 1.0, 2.0 Point1, 2 1.0, 2.0 Point1, 2 Point0, 1 True Point1, 1 Point1, 1 True Point0.5, 1 Point0.5, 1 False Pointpi, e Traceback most recent call last: ... ValueError: could not convert string to float: 'pi' constructs a list of points from an arraylike object of numbers Arguments listoftuples: arraylike object of type numbers. Acceptable types so far are lists, tuples and sets. Returns points: a list where each item is of type Point. This contains only objects which can be converted into a Point. Examples constructpoints1, 1, 2, 1, 0.3, 4 1.0, 1.0, 2.0, 1.0, 0.3, 4.0 constructpoints1, 2 Ignoring deformed point 1. All points must have at least 2 coordinates. Ignoring deformed point 2. All points must have at least 2 coordinates. constructpoints constructpointsNone validates an input instance before a convexhull algorithms uses it Parameters points: arraylike, the 2d points to validate before using with a convexhull algorithm. The elements of points must be either lists, tuples or Points. Returns points: arraylike, an iterable of all welldefined Points constructed passed in. Exception ValueError: if points is empty or None, or if a wrong data structure like a scalar is passed TypeError: if an iterable but nonindexable object eg. dictionary is passed. The exception to this a set which we'll convert to a list before using Examples validateinput1, 2 1.0, 2.0 validateinput1, 2 1.0, 2.0 validateinputPoint2, 1, Point1, 2 2.0, 1.0, 1.0, 2.0 validateinput Traceback most recent call last: ... ValueError: Expecting a list of points but got validateinput1 Traceback most recent call last: ... ValueError: Expecting an iterable object but got an noniterable type 1 Computes the sign perpendicular distance of a 2d point c from a line segment ab. The sign indicates the direction of c relative to ab. A Positive value means c is above ab to the left, while a negative value means c is below ab to the right. 0 means all three points are on a straight line. As a side note, 0.5 absdet is the area of triangle abc Parameters a: point, the point on the left end of line segment ab b: point, the point on the right end of line segment ab c: point, the point for which the direction and location is desired. Returns det: float, absdet is the distance of c from ab. The sign indicates which side of line segment ab c is. det is computed as axby cxay bxcy aybx cyax bycx Examples detPoint1, 1, Point1, 2, Point1, 5 0.0 detPoint0, 0, Point10, 0, Point0, 10 100.0 detPoint0, 0, Point10, 0, Point0, 10 100.0 Constructs the convex hull of a set of 2D points using a brute force algorithm. The algorithm basically considers all combinations of points i, j and uses the definition of convexity to determine whether i, j is part of the convex hull or not. i, j is part of the convex hull if and only iff there are no points on both sides of the line segment connecting the ij, and there is no point k such that k is on either end of the ij. Runtime: On3 definitely horrible Parameters points: arraylike of object of Points, lists or tuples. The set of 2d points for which the convexhull is needed Returns convexset: list, the convexhull of points sorted in nondecreasing order. See Also convexhullrecursive, Examples convexhullbf0, 0, 1, 0, 10, 1 0.0, 0.0, 1.0, 0.0, 10.0, 1.0 convexhullbf0, 0, 1, 0, 10, 0 0.0, 0.0, 10.0, 0.0 convexhullbf1, 1,1, 1, 0, 0, 0.5, 0.5, 1, 1, 1, 1, ... 0.75, 1 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 convexhullbf0, 3, 2, 2, 1, 1, 2, 1, 3, 0, 0, 0, 3, 3, ... 2, 1, 2, 4, 1, 3 0.0, 0.0, 0.0, 3.0, 1.0, 3.0, 2.0, 4.0, 3.0, 0.0, 3.0, 3.0 pointi, pointj, pointk all lie on a straight line if pointk is to the left of pointi or it's to the right of pointj, then pointi, pointj cannot be part of the convex hull of A Constructs the convex hull of a set of 2D points using a divideandconquer strategy The algorithm exploits the geometric properties of the problem by repeatedly partitioning the set of points into smaller hulls, and finding the convex hull of these smaller hulls. The union of the convex hull from smaller hulls is the solution to the convex hull of the larger problem. Parameter points: arraylike of object of Points, lists or tuples. The set of 2d points for which the convexhull is needed Runtime: On log n Returns convexset: list, the convexhull of points sorted in nondecreasing order. Examples convexhullrecursive0, 0, 1, 0, 10, 1 0.0, 0.0, 1.0, 0.0, 10.0, 1.0 convexhullrecursive0, 0, 1, 0, 10, 0 0.0, 0.0, 10.0, 0.0 convexhullrecursive1, 1,1, 1, 0, 0, 0.5, 0.5, 1, 1, 1, 1, ... 0.75, 1 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 convexhullrecursive0, 3, 2, 2, 1, 1, 2, 1, 3, 0, 0, 0, 3, 3, ... 2, 1, 2, 4, 1, 3 0.0, 0.0, 0.0, 3.0, 1.0, 3.0, 2.0, 4.0, 3.0, 0.0, 3.0, 3.0 divide all the points into an upper hull and a lower hull the left most point and the right most point are definitely members of the convex hull by definition. use these two anchors to divide all the points into two hulls, an upper hull and a lower hull. all points to the left above the line joining the extreme points belong to the upper hull all points to the right below the line joining the extreme points below to the lower hull ignore all points on the line joining the extreme points since they cannot be part of the convex hull Parameters points: list or None, the hull of points from which to choose the next convexhull point left: Point, the point to the left of line segment joining left and right right: The point to the right of the line segment joining left and right convexset: set, the current convexhull. The state of convexset gets updated by this function Note For the line segment 'ab', 'a' is on the left and 'b' on the right. but the reverse is true for the line segment 'ba'. Returns Nothing, only updates the state of convexset Constructs the convex hull of a set of 2D points using the melkman algorithm. The algorithm works by iteratively inserting points of a simple polygonal chain meaning that no line segments between two consecutive points cross each other. Sorting the points yields such a polygonal chain. For a detailed description, see http:cgm.cs.mcgill.caathenscs601Melkman.html Runtime: On log n On if points are already sorted in the input Parameters points: arraylike of object of Points, lists or tuples. The set of 2d points for which the convexhull is needed Returns convexset: list, the convexhull of points sorted in nondecreasing order. See Also Examples convexhullmelkman0, 0, 1, 0, 10, 1 0.0, 0.0, 1.0, 0.0, 10.0, 1.0 convexhullmelkman0, 0, 1, 0, 10, 0 0.0, 0.0, 10.0, 0.0 convexhullmelkman1, 1,1, 1, 0, 0, 0.5, 0.5, 1, 1, 1, 1, ... 0.75, 1 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 convexhullmelkman0, 3, 2, 2, 1, 1, 2, 1, 3, 0, 0, 0, 3, 3, ... 2, 1, 2, 4, 1, 3 0.0, 0.0, 0.0, 3.0, 1.0, 3.0, 2.0, 4.0, 3.0, 0.0, 3.0, 3.0 The point lies within the convex hull convexhull is contains the convex hull in circular order the convex set of points is 0, 0, 0, 3, 1, 3, 2, 4, 3, 0, 3, 3
from __future__ import annotations from collections.abc import Iterable class Point: """ Defines a 2-d point for use by all convex-hull algorithms. Parameters ---------- x: an int or a float, the x-coordinate of the 2-d point y: an int or a float, the y-coordinate of the 2-d point Examples -------- >>> Point(1, 2) (1.0, 2.0) >>> Point("1", "2") (1.0, 2.0) >>> Point(1, 2) > Point(0, 1) True >>> Point(1, 1) == Point(1, 1) True >>> Point(-0.5, 1) == Point(0.5, 1) False >>> Point("pi", "e") Traceback (most recent call last): ... ValueError: could not convert string to float: 'pi' """ def __init__(self, x, y): self.x, self.y = float(x), float(y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self == other def __gt__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y > other.y return False def __lt__(self, other): return not self > other def __ge__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y >= other.y return False def __le__(self, other): if self.x < other.x: return True elif self.x == other.x: return self.y <= other.y return False def __repr__(self): return f"({self.x}, {self.y})" def __hash__(self): return hash(self.x) def _construct_points( list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]], ) -> list[Point]: """ constructs a list of points from an array-like object of numbers Arguments --------- list_of_tuples: array-like object of type numbers. Acceptable types so far are lists, tuples and sets. Returns -------- points: a list where each item is of type Point. This contains only objects which can be converted into a Point. Examples ------- >>> _construct_points([[1, 1], [2, -1], [0.3, 4]]) [(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)] >>> _construct_points([1, 2]) Ignoring deformed point 1. All points must have at least 2 coordinates. Ignoring deformed point 2. All points must have at least 2 coordinates. [] >>> _construct_points([]) [] >>> _construct_points(None) [] """ points: list[Point] = [] if list_of_tuples: for p in list_of_tuples: if isinstance(p, Point): points.append(p) else: try: points.append(Point(p[0], p[1])) except (IndexError, TypeError): print( f"Ignoring deformed point {p}. All points" " must have at least 2 coordinates." ) return points def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]: """ validates an input instance before a convex-hull algorithms uses it Parameters --------- points: array-like, the 2d points to validate before using with a convex-hull algorithm. The elements of points must be either lists, tuples or Points. Returns ------- points: array_like, an iterable of all well-defined Points constructed passed in. Exception --------- ValueError: if points is empty or None, or if a wrong data structure like a scalar is passed TypeError: if an iterable but non-indexable object (eg. dictionary) is passed. The exception to this a set which we'll convert to a list before using Examples ------- >>> _validate_input([[1, 2]]) [(1.0, 2.0)] >>> _validate_input([(1, 2)]) [(1.0, 2.0)] >>> _validate_input([Point(2, 1), Point(-1, 2)]) [(2.0, 1.0), (-1.0, 2.0)] >>> _validate_input([]) Traceback (most recent call last): ... ValueError: Expecting a list of points but got [] >>> _validate_input(1) Traceback (most recent call last): ... ValueError: Expecting an iterable object but got an non-iterable type 1 """ if not hasattr(points, "__iter__"): msg = f"Expecting an iterable object but got an non-iterable type {points}" raise ValueError(msg) if not points: msg = f"Expecting a list of points but got {points}" raise ValueError(msg) return _construct_points(points) def _det(a: Point, b: Point, c: Point) -> float: """ Computes the sign perpendicular distance of a 2d point c from a line segment ab. The sign indicates the direction of c relative to ab. A Positive value means c is above ab (to the left), while a negative value means c is below ab (to the right). 0 means all three points are on a straight line. As a side note, 0.5 * abs|det| is the area of triangle abc Parameters ---------- a: point, the point on the left end of line segment ab b: point, the point on the right end of line segment ab c: point, the point for which the direction and location is desired. Returns -------- det: float, abs(det) is the distance of c from ab. The sign indicates which side of line segment ab c is. det is computed as (a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x) Examples ---------- >>> _det(Point(1, 1), Point(1, 2), Point(1, 5)) 0.0 >>> _det(Point(0, 0), Point(10, 0), Point(0, 10)) 100.0 >>> _det(Point(0, 0), Point(10, 0), Point(0, -10)) -100.0 """ det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x) return det def convex_hull_bf(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using a brute force algorithm. The algorithm basically considers all combinations of points (i, j) and uses the definition of convexity to determine whether (i, j) is part of the convex hull or not. (i, j) is part of the convex hull if and only iff there are no points on both sides of the line segment connecting the ij, and there is no point k such that k is on either end of the ij. Runtime: O(n^3) - definitely horrible Parameters --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Returns ------ convex_set: list, the convex-hull of points sorted in non-decreasing order. See Also -------- convex_hull_recursive, Examples --------- >>> convex_hull_bf([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_bf([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) convex_set = set() for i in range(n - 1): for j in range(i + 1, n): points_left_of_ij = points_right_of_ij = False ij_part_of_convex_hull = True for k in range(n): if k not in {i, j}: det_k = _det(points[i], points[j], points[k]) if det_k > 0: points_left_of_ij = True elif det_k < 0: points_right_of_ij = True else: # point[i], point[j], point[k] all lie on a straight line # if point[k] is to the left of point[i] or it's to the # right of point[j], then point[i], point[j] cannot be # part of the convex hull of A if points[k] < points[i] or points[k] > points[j]: ij_part_of_convex_hull = False break if points_left_of_ij and points_right_of_ij: ij_part_of_convex_hull = False break if ij_part_of_convex_hull: convex_set.update([points[i], points[j]]) return sorted(convex_set) def convex_hull_recursive(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy The algorithm exploits the geometric properties of the problem by repeatedly partitioning the set of points into smaller hulls, and finding the convex hull of these smaller hulls. The union of the convex hull from smaller hulls is the solution to the convex hull of the larger problem. Parameter --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Runtime: O(n log n) Returns ------- convex_set: list, the convex-hull of points sorted in non-decreasing order. Examples --------- >>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) # divide all the points into an upper hull and a lower hull # the left most point and the right most point are definitely # members of the convex hull by definition. # use these two anchors to divide all the points into two hulls, # an upper hull and a lower hull. # all points to the left (above) the line joining the extreme points belong to the # upper hull # all points to the right (below) the line joining the extreme points below to the # lower hull # ignore all points on the line joining the extreme points since they cannot be # part of the convex hull left_most_point = points[0] right_most_point = points[n - 1] convex_set = {left_most_point, right_most_point} upper_hull = [] lower_hull = [] for i in range(1, n - 1): det = _det(left_most_point, right_most_point, points[i]) if det > 0: upper_hull.append(points[i]) elif det < 0: lower_hull.append(points[i]) _construct_hull(upper_hull, left_most_point, right_most_point, convex_set) _construct_hull(lower_hull, right_most_point, left_most_point, convex_set) return sorted(convex_set) def _construct_hull( points: list[Point], left: Point, right: Point, convex_set: set[Point] ) -> None: """ Parameters --------- points: list or None, the hull of points from which to choose the next convex-hull point left: Point, the point to the left of line segment joining left and right right: The point to the right of the line segment joining left and right convex_set: set, the current convex-hull. The state of convex-set gets updated by this function Note ---- For the line segment 'ab', 'a' is on the left and 'b' on the right. but the reverse is true for the line segment 'ba'. Returns ------- Nothing, only updates the state of convex-set """ if points: extreme_point = None extreme_point_distance = float("-inf") candidate_points = [] for p in points: det = _det(left, right, p) if det > 0: candidate_points.append(p) if det > extreme_point_distance: extreme_point_distance = det extreme_point = p if extreme_point: _construct_hull(candidate_points, left, extreme_point, convex_set) convex_set.add(extreme_point) _construct_hull(candidate_points, extreme_point, right, convex_set) def convex_hull_melkman(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using the melkman algorithm. The algorithm works by iteratively inserting points of a simple polygonal chain (meaning that no line segments between two consecutive points cross each other). Sorting the points yields such a polygonal chain. For a detailed description, see http://cgm.cs.mcgill.ca/~athens/cs601/Melkman.html Runtime: O(n log n) - O(n) if points are already sorted in the input Parameters --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Returns ------ convex_set: list, the convex-hull of points sorted in non-decreasing order. See Also -------- Examples --------- >>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) convex_hull = points[:2] for i in range(2, n): det = _det(convex_hull[1], convex_hull[0], points[i]) if det > 0: convex_hull.insert(0, points[i]) break elif det < 0: convex_hull.append(points[i]) break else: convex_hull[1] = points[i] i += 1 for j in range(i, n): if ( _det(convex_hull[0], convex_hull[-1], points[j]) > 0 and _det(convex_hull[-1], convex_hull[0], points[1]) < 0 ): # The point lies within the convex hull continue convex_hull.insert(0, points[j]) convex_hull.append(points[j]) while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0: del convex_hull[1] while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0: del convex_hull[-2] # `convex_hull` is contains the convex hull in circular order return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull) def main(): points = [ (0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), (2, -1), (2, -4), (1, -3), ] # the convex set of points is # [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)] results_bf = convex_hull_bf(points) results_recursive = convex_hull_recursive(points) assert results_bf == results_recursive results_melkman = convex_hull_melkman(points) assert results_bf == results_melkman print(results_bf) if __name__ == "__main__": main()
Heap's algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https:en.wikipedia.orgwikiHeap27salgorithm. Pure python implementation of the Heap's algorithm recursive version, returning all permutations of a list. heaps heaps0 0, heaps1, 1 1, 1, 1, 1 heaps1, 2, 3 1, 2, 3, 2, 1, 3, 3, 1, 2, 1, 3, 2, 2, 3, 1, 3, 2, 1 from itertools import permutations sortedheaps1,2,3 sortedpermutations1,2,3 True allsortedheapsx sortedpermutationsx ... for x in , 0, 1, 1, 1, 2, 3 True
def heaps(arr: list) -> list: """ Pure python implementation of the Heap's algorithm (recursive version), returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(k: int, arr: list): if k == 1: res.append(tuple(arr[:])) return generate(k - 1, arr) for i in range(k - 1): if k % 2 == 0: # k is even arr[i], arr[k - 1] = arr[k - 1], arr[i] else: # k is odd arr[0], arr[k - 1] = arr[k - 1], arr[0] generate(k - 1, arr) generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
Heap's iterative algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https:en.wikipedia.orgwikiHeap27salgorithm. Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. heaps heaps0 0, heaps1, 1 1, 1, 1, 1 heaps1, 2, 3 1, 2, 3, 2, 1, 3, 3, 1, 2, 1, 3, 2, 2, 3, 1, 3, 2, 1 from itertools import permutations sortedheaps1,2,3 sortedpermutations1,2,3 True allsortedheapsx sortedpermutationsx ... for x in , 0, 1, 1, 1, 2, 3 True
def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
Given an arraylike data structure A1..n, how many pairs i, j for all 1 i j n such that Ai Aj? These pairs are called inversions. Counting the number of such inversions in an arraylike object is the important. Among other things, counting inversions can help us determine how close a given array is to being sorted. In this implementation, I provide two algorithms, a divideandconquer algorithm which runs in nlogn and the bruteforce n2 algorithm. Counts the number of inversions using a naive bruteforce algorithm Parameters arr: arr: arraylike, the list containing the items for which the number of inversions is desired. The elements of arr must be comparable. Returns numinversions: The total number of inversions in arr Examples countinversionsbf1, 4, 2, 4, 1 4 countinversionsbf1, 1, 2, 4, 4 0 countinversionsbf 0 Counts the number of inversions using a divideandconquer algorithm Parameters arr: arraylike, the list containing the items for which the number of inversions is desired. The elements of arr must be comparable. Returns C: a sorted copy of arr. numinversions: int, the total number of inversions in 'arr' Examples countinversionsrecursive1, 4, 2, 4, 1 1, 1, 2, 4, 4, 4 countinversionsrecursive1, 1, 2, 4, 4 1, 1, 2, 4, 4, 0 countinversionsrecursive , 0 Counts the inversions across two sorted arrays. And combine the two arrays into one sorted array For all 1 ilenP and for all 1 j lenQ, if Pi Qj, then i, j is a cross inversion Parameters P: arraylike, sorted in nondecreasing order Q: arraylike, sorted in nondecreasing order Returns R: arraylike, a sorted array of the elements of P and Q numinversion: int, the number of inversions across P and Q Examples countcrossinversions1, 2, 3, 0, 2, 5 0, 1, 2, 2, 3, 5, 4 countcrossinversions1, 2, 3, 3, 4, 5 1, 2, 3, 3, 4, 5, 0 if P1 Qj, then Pk Qk for all i k lenP These are all inversions. The claim emerges from the property that P is sorted. this arr has 8 inversions: 10, 2, 10, 1, 10, 5, 10, 5, 10, 2, 2, 1, 5, 2, 5, 2 testing an array with zero inversion a sorted arr1 an empty list should also have zero inversions
def count_inversions_bf(arr): """ Counts the number of inversions using a naive brute-force algorithm Parameters ---------- arr: arr: array-like, the list containing the items for which the number of inversions is desired. The elements of `arr` must be comparable. Returns ------- num_inversions: The total number of inversions in `arr` Examples --------- >>> count_inversions_bf([1, 4, 2, 4, 1]) 4 >>> count_inversions_bf([1, 1, 2, 4, 4]) 0 >>> count_inversions_bf([]) 0 """ num_inversions = 0 n = len(arr) for i in range(n - 1): for j in range(i + 1, n): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def count_inversions_recursive(arr): """ Counts the number of inversions using a divide-and-conquer algorithm Parameters ----------- arr: array-like, the list containing the items for which the number of inversions is desired. The elements of `arr` must be comparable. Returns ------- C: a sorted copy of `arr`. num_inversions: int, the total number of inversions in 'arr' Examples -------- >>> count_inversions_recursive([1, 4, 2, 4, 1]) ([1, 1, 2, 4, 4], 4) >>> count_inversions_recursive([1, 1, 2, 4, 4]) ([1, 1, 2, 4, 4], 0) >>> count_inversions_recursive([]) ([], 0) """ if len(arr) <= 1: return arr, 0 mid = len(arr) // 2 p = arr[0:mid] q = arr[mid:] a, inversion_p = count_inversions_recursive(p) b, inversions_q = count_inversions_recursive(q) c, cross_inversions = _count_cross_inversions(a, b) num_inversions = inversion_p + inversions_q + cross_inversions return c, num_inversions def _count_cross_inversions(p, q): """ Counts the inversions across two sorted arrays. And combine the two arrays into one sorted array For all 1<= i<=len(P) and for all 1 <= j <= len(Q), if P[i] > Q[j], then (i, j) is a cross inversion Parameters ---------- P: array-like, sorted in non-decreasing order Q: array-like, sorted in non-decreasing order Returns ------ R: array-like, a sorted array of the elements of `P` and `Q` num_inversion: int, the number of inversions across `P` and `Q` Examples -------- >>> _count_cross_inversions([1, 2, 3], [0, 2, 5]) ([0, 1, 2, 2, 3, 5], 4) >>> _count_cross_inversions([1, 2, 3], [3, 4, 5]) ([1, 2, 3, 3, 4, 5], 0) """ r = [] i = j = num_inversion = 0 while i < len(p) and j < len(q): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(p) - i r.append(q[j]) j += 1 else: r.append(p[i]) i += 1 if i < len(p): r.extend(p[i:]) else: r.extend(q[j:]) return r, num_inversion def main(): arr_1 = [10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 8 print("number of inversions = ", num_inversions_bf) # testing an array with zero inversion (a sorted arr_1) arr_1.sort() num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = ", num_inversions_bf) # an empty list should also have zero inversions arr_1 = [] num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = ", num_inversions_bf) if __name__ == "__main__": main()
Find the kth smallest element in linear time using divide and conquer. Recall we can do this trivially in Onlogn time. Sort the list and access kth element in constant time. This is a divide and conquer algorithm that can find a solution in On time. For more information of this algorithm: https:web.stanford.educlassarchivecscs161cs161.1138lectures08Small08.pdf Choose a random pivot for the list. We can use a more sophisticated algorithm here, such as the medianofmedians algorithm. Return the kth smallest number in lst. kthnumber2, 1, 3, 4, 5, 3 3 kthnumber2, 1, 3, 4, 5, 1 1 kthnumber2, 1, 3, 4, 5, 5 5 kthnumber3, 2, 5, 6, 7, 8, 2 3 kthnumber25, 21, 98, 100, 76, 22, 43, 60, 89, 87, 4 43 pick a pivot and separate into list based on pivot. partition based on pivot linear time if we get lucky, pivot might be the element we want. we can easily see this: small elements smaller than k pivot kth element big elements larger than k pivot is in elements bigger than k pivot is in elements smaller than k
from __future__ import annotations from random import choice def random_pivot(lst): """ Choose a random pivot for the list. We can use a more sophisticated algorithm here, such as the median-of-medians algorithm. """ return choice(lst) def kth_number(lst: list[int], k: int) -> int: """ Return the kth smallest number in lst. >>> kth_number([2, 1, 3, 4, 5], 3) 3 >>> kth_number([2, 1, 3, 4, 5], 1) 1 >>> kth_number([2, 1, 3, 4, 5], 5) 5 >>> kth_number([3, 2, 5, 6, 7, 8], 2) 3 >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4) 43 """ # pick a pivot and separate into list based on pivot. pivot = random_pivot(lst) # partition based on pivot # linear time small = [e for e in lst if e < pivot] big = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(small) == k - 1: return pivot # pivot is in elements bigger than k elif len(small) < k - 1: return kth_number(big, k - len(small) - 1) # pivot is in elements smaller than k else: return kth_number(small, k) if __name__ == "__main__": import doctest doctest.testmod()
We are given an array A1..n of integers, n 1. We want to find a pair of indices i, j such that 1 i j n and Aj Ai is as large as possible. Explanation: https:www.geeksforgeeks.orgmaximumdifferencebetweentwoelements maxdifference5, 11, 2, 1, 7, 9, 0, 7 1, 9 base case split A into half. 2 sub problems, 12 of original size. get min of first and max of second linear time 3 cases, either small1, big1, minfirst, maxsecond, small2, big2 constant comparisons
def max_difference(a: list[int]) -> tuple[int, int]: """ We are given an array A[1..n] of integers, n >= 1. We want to find a pair of indices (i, j) such that 1 <= i <= j <= n and A[j] - A[i] is as large as possible. Explanation: https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ >>> max_difference([5, 11, 2, 1, 7, 9, 0, 7]) (1, 9) """ # base case if len(a) == 1: return a[0], a[0] else: # split A into half. first = a[: len(a) // 2] second = a[len(a) // 2 :] # 2 sub problems, 1/2 of original size. small1, big1 = max_difference(first) small2, big2 = max_difference(second) # get min of first and max of second # linear time min_first = min(first) max_second = max(second) # 3 cases, either (small1, big1), # (min_first, max_second), (small2, big2) # constant comparisons if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1: return small2, big2 elif big1 - small1 > max_second - min_first: return small1, big1 else: return min_first, max_second if __name__ == "__main__": import doctest doctest.testmod()
The maximum subarray problem is the task of finding the continuous subarray that has the maximum sum within a given array of numbers. For example, given the array 2, 1, 3, 4, 1, 2, 1, 5, 4, the contiguous subarray with the maximum sum is 4, 1, 2, 1, which has a sum of 6. This divideandconquer algorithm finds the maximum subarray in On log n time. Solves the maximum subarray problem using divide and conquer. :param arr: the given array of numbers :param low: the start index :param high: the end index :return: the start index of the maximum subarray, the end index of the maximum subarray, and the maximum subarray sum nums 2, 1, 3, 4, 1, 2, 1, 5, 4 maxsubarraynums, 0, lennums 1 3, 6, 6 nums 2, 8, 9 maxsubarraynums, 0, lennums 1 0, 2, 19 nums 0, 0 maxsubarraynums, 0, lennums 1 0, 0, 0 nums 1.0, 0.0, 1.0 maxsubarraynums, 0, lennums 1 2, 2, 1.0 nums 2, 3, 1, 4, 6 maxsubarraynums, 0, lennums 1 2, 2, 1 maxsubarray, 0, 0 None, None, 0 A random simulation of this algorithm.
from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def max_subarray( arr: Sequence[float], low: int, high: int ) -> tuple[int | None, int | None, float]: """ Solves the maximum subarray problem using divide and conquer. :param arr: the given array of numbers :param low: the start index :param high: the end index :return: the start index of the maximum subarray, the end index of the maximum subarray, and the maximum subarray sum >>> nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] >>> max_subarray(nums, 0, len(nums) - 1) (3, 6, 6) >>> nums = [2, 8, 9] >>> max_subarray(nums, 0, len(nums) - 1) (0, 2, 19) >>> nums = [0, 0] >>> max_subarray(nums, 0, len(nums) - 1) (0, 0, 0) >>> nums = [-1.0, 0.0, 1.0] >>> max_subarray(nums, 0, len(nums) - 1) (2, 2, 1.0) >>> nums = [-2, -3, -1, -4, -6] >>> max_subarray(nums, 0, len(nums) - 1) (2, 2, -1) >>> max_subarray([], 0, 0) (None, None, 0) """ if not arr: return None, None, 0 if low == high: return low, high, arr[low] mid = (low + high) // 2 left_low, left_high, left_sum = max_subarray(arr, low, mid) right_low, right_high, right_sum = max_subarray(arr, mid + 1, high) cross_left, cross_right, cross_sum = max_cross_sum(arr, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def max_cross_sum( arr: Sequence[float], low: int, mid: int, high: int ) -> tuple[int, int, float]: left_sum, max_left = float("-inf"), -1 right_sum, max_right = float("-inf"), -1 summ: int | float = 0 for i in range(mid, low - 1, -1): summ += arr[i] if summ > left_sum: left_sum = summ max_left = i summ = 0 for i in range(mid + 1, high + 1): summ += arr[i] if summ > right_sum: right_sum = summ max_right = i return max_left, max_right, (left_sum + right_sum) def time_max_subarray(input_size: int) -> float: arr = [randint(1, input_size) for _ in range(input_size)] start = time.time() max_subarray(arr, 0, input_size - 1) end = time.time() return end - start def plot_runtimes() -> None: input_sizes = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] runtimes = [time_max_subarray(input_size) for input_size in input_sizes] print("No of Inputs\t\tTime Taken") for input_size, runtime in zip(input_sizes, runtimes): print(input_size, "\t\t", runtime) plt.plot(input_sizes, runtimes) plt.xlabel("Number of Inputs") plt.ylabel("Time taken in seconds") plt.show() if __name__ == "__main__": """ A random simulation of this algorithm. """ from doctest import testmod testmod()
Helper function for mergesort. lefthalf 2 righthalf 1 mergelefthalf, righthalf 2, 1 lefthalf 1,2,3 righthalf 4,5,6 mergelefthalf, righthalf 1, 2, 3, 4, 5, 6 lefthalf 2 righthalf 1 mergelefthalf, righthalf 2, 1 lefthalf 12, 15 righthalf 13, 14 mergelefthalf, righthalf 12, 13, 14, 15 lefthalf righthalf mergelefthalf, righthalf Returns a list of sorted array elements using merge sort. from random import shuffle array 2, 3, 10, 11, 99, 100000, 100, 200 shufflearray mergesortarray 200, 10, 2, 3, 11, 99, 100, 100000 shufflearray mergesortarray 200, 10, 2, 3, 11, 99, 100, 100000 array 200 mergesortarray 200 array 2, 3, 10, 11, 99, 100000, 100, 200 shufflearray sortedarray mergesortarray True array 2 mergesortarray 2 array mergesortarray array 10000000, 1, 1111111111, 101111111112, 9000002 sortedarray mergesortarray True the actual formula to calculate the middle element left right left 2 this avoids integer overflow in case of large N Split the array into halves till the array length becomes equal to One merge the arrays of single length returned by mergeSort function and pass them into the merge arrays function which merges the array
from __future__ import annotations def merge(left_half: list, right_half: list) -> list: """Helper function for mergesort. >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [1,2,3] >>> right_half = [4,5,6] >>> merge(left_half, right_half) [1, 2, 3, 4, 5, 6] >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [12, 15] >>> right_half = [13, 14] >>> merge(left_half, right_half) [12, 13, 14, 15] >>> left_half = [] >>> right_half = [] >>> merge(left_half, right_half) [] """ sorted_array = [None] * (len(right_half) + len(left_half)) pointer1 = 0 # pointer to current index for left Half pointer2 = 0 # pointer to current index for the right Half index = 0 # pointer to current index for the sorted array Half while pointer1 < len(left_half) and pointer2 < len(right_half): if left_half[pointer1] < right_half[pointer2]: sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 else: sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 while pointer1 < len(left_half): sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 while pointer2 < len(right_half): sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 return sorted_array def merge_sort(array: list) -> list: """Returns a list of sorted array elements using merge sort. >>> from random import shuffle >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> array = [-200] >>> merge_sort(array) [-200] >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> sorted(array) == merge_sort(array) True >>> array = [-2] >>> merge_sort(array) [-2] >>> array = [] >>> merge_sort(array) [] >>> array = [10000000, 1, -1111111111, 101111111112, 9000002] >>> sorted(array) == merge_sort(array) True """ if len(array) <= 1: return array # the actual formula to calculate the middle element = left + (right - left) // 2 # this avoids integer overflow in case of large N middle = 0 + (len(array) - 0) // 2 # Split the array into halves till the array length becomes equal to One # merge the arrays of single length returned by mergeSort function and # pass them into the merge arrays function which merges the array left_half = array[:middle] right_half = array[middle:] return merge(merge_sort(left_half), merge_sort(right_half)) if __name__ == "__main__": import doctest doctest.testmod()
Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. for p 1 An obvious solution can be performed in On, to find the maximum of the array. From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1 Return the peak value of lst. peak1, 2, 3, 4, 5, 4, 3, 2, 1 5 peak1, 10, 9, 8, 7, 6, 5, 4 10 peak1, 9, 8, 7 9 peak1, 2, 3, 4, 5, 6, 7, 0 7 peak1, 2, 3, 4, 3, 2, 1, 0, 1, 2 4 middle index choose the middle 3 elements if middle element is peak if increasing, recurse on right decreasing
from __future__ import annotations def peak(lst: list[int]) -> int: """ Return the peak value of `lst`. >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) 5 >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) 10 >>> peak([1, 9, 8, 7]) 9 >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) 7 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) 4 """ # middle index m = len(lst) // 2 # choose the middle 3 elements three = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) # decreasing else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) if __name__ == "__main__": import doctest doctest.testmod()
Function using divide and conquer to calculate ab. It only works for integer a,b. power4,6 4096 power2,3 8 power2,3 8 power2,3 0.125 power2,3 0.125
def actual_power(a: int, b: int): """ Function using divide and conquer to calculate a^b. It only works for integer a,b. """ if b == 0: return 1 if (b % 2) == 0: return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) else: return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) def power(a: int, b: int) -> float: """ >>> power(4,6) 4096 >>> power(2,3) 8 >>> power(-2,3) -8 >>> power(2,-3) 0.125 >>> power(-2,-3) -0.125 """ if b < 0: return 1 / actual_power(a, b) return actual_power(a, b) if __name__ == "__main__": print(power(-2, -3))
Multiplication only for 2x2 matrices Given an even length matrix, returns the topleft, topright, botleft, botright quadrant. splitmatrix4,3,2,4,2,3,1,1,6,5,4,3,8,4,1,6 4, 3, 2, 3, 2, 4, 1, 1, 6, 5, 8, 4, 4, 3, 1, 6 splitmatrix ... 4,3,2,4,4,3,2,4,2,3,1,1,2,3,1,1,6,5,4,3,6,5,4,3,8,4,1,6,8,4,1,6, ... 4,3,2,4,4,3,2,4,2,3,1,1,2,3,1,1,6,5,4,3,6,5,4,3,8,4,1,6,8,4,1,6 ... doctest: NORMALIZEWHITESPACE 4, 3, 2, 4, 2, 3, 1, 1, 6, 5, 4, 3, 8, 4, 1, 6, 4, 3, 2, 4, 2, 3, 1, 1, 6, 5, 4, 3, 8, 4, 1, 6, 4, 3, 2, 4, 2, 3, 1, 1, 6, 5, 4, 3, 8, 4, 1, 6, 4, 3, 2, 4, 2, 3, 1, 1, 6, 5, 4, 3, 8, 4, 1, 6 Recursive function to calculate the product of two matrices, using the Strassen Algorithm. It only supports square matrices of any size that is a power of 2. construct the new matrix from our 4 quadrants strassen2,1,3,3,4,6,1,4,2,7,6,7, 4,2,3,4,2,1,1,1,8,6,4,2 34, 23, 19, 15, 68, 46, 37, 28, 28, 18, 15, 12, 96, 62, 55, 48 strassen3,7,5,6,9,1,5,3,7,8,1,4,4,5,7, 2,4,5,2,1,7,5,5,7,8 139, 163, 121, 134, 100, 121 Adding zeros to the matrices to convert them both into square matrices of equal dimensions that are a power of 2 Removing the additional zeros
from __future__ import annotations import math def default_matrix_multiplication(a: list, b: list) -> list: """ Multiplication only for 2x2 matrices """ if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2: raise Exception("Matrices are not 2x2") new_matrix = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def matrix_addition(matrix_a: list, matrix_b: list): return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row]))] for row in range(len(matrix_a)) ] def matrix_subtraction(matrix_a: list, matrix_b: list): return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row]))] for row in range(len(matrix_a)) ] def split_matrix(a: list) -> tuple[list, list, list, list]: """ Given an even length matrix, returns the top_left, top_right, bot_left, bot_right quadrant. >>> split_matrix([[4,3,2,4],[2,3,1,1],[6,5,4,3],[8,4,1,6]]) ([[4, 3], [2, 3]], [[2, 4], [1, 1]], [[6, 5], [8, 4]], [[4, 3], [1, 6]]) >>> split_matrix([ ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6], ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6] ... ]) # doctest: +NORMALIZE_WHITESPACE ([[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]]) """ if len(a) % 2 != 0 or len(a[0]) % 2 != 0: raise Exception("Odd matrices are not supported!") matrix_length = len(a) mid = matrix_length // 2 top_right = [[a[i][j] for j in range(mid, matrix_length)] for i in range(mid)] bot_right = [ [a[i][j] for j in range(mid, matrix_length)] for i in range(mid, matrix_length) ] top_left = [[a[i][j] for j in range(mid)] for i in range(mid)] bot_left = [[a[i][j] for j in range(mid)] for i in range(mid, matrix_length)] return top_left, top_right, bot_left, bot_right def matrix_dimensions(matrix: list) -> tuple[int, int]: return len(matrix), len(matrix[0]) def print_matrix(matrix: list) -> None: print("\n".join(str(line) for line in matrix)) def actual_strassen(matrix_a: list, matrix_b: list) -> list: """ Recursive function to calculate the product of two matrices, using the Strassen Algorithm. It only supports square matrices of any size that is a power of 2. """ if matrix_dimensions(matrix_a) == (2, 2): return default_matrix_multiplication(matrix_a, matrix_b) a, b, c, d = split_matrix(matrix_a) e, f, g, h = split_matrix(matrix_b) t1 = actual_strassen(a, matrix_subtraction(f, h)) t2 = actual_strassen(matrix_addition(a, b), h) t3 = actual_strassen(matrix_addition(c, d), e) t4 = actual_strassen(d, matrix_subtraction(g, e)) t5 = actual_strassen(matrix_addition(a, d), matrix_addition(e, h)) t6 = actual_strassen(matrix_subtraction(b, d), matrix_addition(g, h)) t7 = actual_strassen(matrix_subtraction(a, c), matrix_addition(e, f)) top_left = matrix_addition(matrix_subtraction(matrix_addition(t5, t4), t2), t6) top_right = matrix_addition(t1, t2) bot_left = matrix_addition(t3, t4) bot_right = matrix_subtraction(matrix_subtraction(matrix_addition(t1, t5), t3), t7) # construct the new matrix from our 4 quadrants new_matrix = [] for i in range(len(top_right)): new_matrix.append(top_left[i] + top_right[i]) for i in range(len(bot_right)): new_matrix.append(bot_left[i] + bot_right[i]) return new_matrix def strassen(matrix1: list, matrix2: list) -> list: """ >>> strassen([[2,1,3],[3,4,6],[1,4,2],[7,6,7]], [[4,2,3,4],[2,1,1,1],[8,6,4,2]]) [[34, 23, 19, 15], [68, 46, 37, 28], [28, 18, 15, 12], [96, 62, 55, 48]] >>> strassen([[3,7,5,6,9],[1,5,3,7,8],[1,4,4,5,7]], [[2,4],[5,2],[1,7],[5,5],[7,8]]) [[139, 163], [121, 134], [100, 121]] """ if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]: msg = ( "Unable to multiply these matrices, please check the dimensions.\n" f"Matrix A: {matrix1}\n" f"Matrix B: {matrix2}" ) raise Exception(msg) dimension1 = matrix_dimensions(matrix1) dimension2 = matrix_dimensions(matrix2) if dimension1[0] == dimension1[1] and dimension2[0] == dimension2[1]: return [matrix1, matrix2] maximum = max(*dimension1, *dimension2) maxim = int(math.pow(2, math.ceil(math.log2(maximum)))) new_matrix1 = matrix1 new_matrix2 = matrix2 # Adding zeros to the matrices to convert them both into square matrices of equal # dimensions that are a power of 2 for i in range(maxim): if i < dimension1[0]: for _ in range(dimension1[1], maxim): new_matrix1[i].append(0) else: new_matrix1.append([0] * maxim) if i < dimension2[0]: for _ in range(dimension2[1], maxim): new_matrix2[i].append(0) else: new_matrix2.append([0] * maxim) final_matrix = actual_strassen(new_matrix1, new_matrix2) # Removing the additional zeros for i in range(maxim): if i < dimension1[0]: for _ in range(dimension2[1], maxim): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": matrix1 = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] matrix2 = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrix1, matrix2))
https:www.hackerrank.comchallengesabbrproblem You can perform the following operation on some string, : 1. Capitalize zero or more of 's lowercase letters at some index i i.e., make them uppercase. 2. Delete all of the remaining lowercase letters in . Example: adaBcd and bABC daBcd capitalize a and cdABCd remove d ABC abbrdaBcd, ABC True abbrdBcd, ABC False
def abbr(a: str, b: str) -> bool: """ >>> abbr("daBcd", "ABC") True >>> abbr("dBcd", "ABC") False """ n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0] = True for i in range(n): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: dp[i + 1][j + 1] = True if a[i].islower(): dp[i + 1][j] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
Program to list all the ways a target string can be constructed from the given list of substrings returns the list containing all the possible combinations a stringtarget can be constructed from the given list of substringswordbank allconstructhello, he, l, o 'he', 'l', 'l', 'o' allconstructpurple,purp,p,ur,le,purpl 'purp', 'le', 'p', 'ur', 'p', 'le' create a table seed value iterate through the indices condition slice condition adds the word to every combination the current position holds now,push that combination to the tableilenword combinations are in reverse order so reverse for better output
from __future__ import annotations def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]: """ returns the list containing all the possible combinations a string(target) can be constructed from the given list of substrings(word_bank) >>> all_construct("hello", ["he", "l", "o"]) [['he', 'l', 'l', 'o']] >>> all_construct("purple",["purp","p","ur","le","purpl"]) [['purp', 'le'], ['p', 'ur', 'p', 'le']] """ word_bank = word_bank or [] # create a table table_size: int = len(target) + 1 table: list[list[list[str]]] = [] for _ in range(table_size): table.append([]) # seed value table[0] = [[]] # because empty string has empty combination # iterate through the indices for i in range(table_size): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(word)] == word: new_combinations: list[list[str]] = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(word)] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(target)]: combination.reverse() return table[len(target)] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
This is a Python implementation for questions involving task assignments between people. Here Bitmasking and DP are used for solving this. Question : We have N tasks and M people. Each person in M can do only certain of these tasks. Also a person can do only one task and a task is performed only by one person. Find the total no of ways in which the tasks can be distributed. DP table will have a dimension of 2MN initially all values are set to 1 finalmask is used to check if all persons are included by setting all bits to 1 if mask self.finalmask all persons are distributed tasks, return 1 if not everyone gets the task and no more tasks are available, return 0 if case already considered Number of ways when we don't this task in the arrangement now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks. if p is already given a task assign this task to p and change the mask value. And recursively assign tasks with the new mask value. save the value. Store the list of persons for each task call the function to fill the DP table, final answer is stored in dp01 the list of tasks that can be done by M persons. For the particular example the tasks can be distributed as 1,2,3, 1,2,4, 1,5,3, 1,5,4, 3,1,4, 3,2,4, 3,5,4, 4,1,3, 4,2,3, 4,5,3 total 10
from collections import defaultdict class AssignmentUsingBitmask: def __init__(self, task_performed, total): self.total_tasks = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 self.dp = [ [-1 for i in range(total + 1)] for j in range(2 ** len(task_performed)) ] self.task = defaultdict(list) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 self.final_mask = (1 << len(task_performed)) - 1 def count_ways_until(self, mask, task_no): # if mask == self.finalmask all persons are distributed tasks, return 1 if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement total_ways_util = self.count_ways_until(mask, task_no + 1) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p), task_no + 1) # save the value. self.dp[mask][task_no] = total_ways_util return self.dp[mask][task_no] def count_no_of_ways(self, task_performed): # Store the list of persons for each task for i in range(len(task_performed)): for j in task_performed[i]: self.task[j].append(i) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0, 1) if __name__ == "__main__": total_tasks = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. task_performed = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) ) """ For the particular example the tasks can be distributed as (1,2,3), (1,2,4), (1,5,3), (1,5,4), (3,1,4), (3,2,4), (3,5,4), (4,1,3), (4,2,3), (4,5,3) total 10 """
Print all the Catalan numbers from 0 to n, n being the user input. The Catalan numbers are a sequence of positive integers that appear in many counting problems in combinatorics 1. Such problems include counting 2: The number of Dyck words of length 2n The number wellformed expressions with n pairs of parentheses e.g., is valid but is not The number of different ways n 1 factors can be completely parenthesized e.g., for n 2, Cn 2 and abc and abc are the two valid ways to parenthesize. The number of full binary trees with n 1 leaves A Catalan number satisfies the following recurrence relation which we will use in this algorithm 1. C0 C1 1 Cn sumCi.Cni1, from i 0 to n1 In addition, the nth Catalan number can be calculated using the closed form formula below 1: Cn 1 n 1 2n choose n Sources: 1 https:brilliant.orgwikicatalannumbers 2 https:en.wikipedia.orgwikiCatalannumber Return a list of the Catalan number sequence from 0 through upperlimit. catalannumbers5 1, 1, 2, 5, 14, 42 catalannumbers2 1, 1, 2 catalannumbers1 Traceback most recent call last: ValueError: Limit for the Catalan sequence must be 0 Base case: C0 C1 1 Recurrence relation: Ci sumCj.Cij1, from j 0 to i
def catalan_numbers(upper_limit: int) -> "list[int]": """ Return a list of the Catalan number sequence from 0 through `upper_limit`. >>> catalan_numbers(5) [1, 1, 2, 5, 14, 42] >>> catalan_numbers(2) [1, 1, 2] >>> catalan_numbers(-1) Traceback (most recent call last): ValueError: Limit for the Catalan sequence must be ≥ 0 """ if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0") catalan_list = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 catalan_list[0] = 1 if upper_limit > 0: catalan_list[1] = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2, upper_limit + 1): for j in range(i): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("\n********* Catalan Numbers Using Dynamic Programming ************\n") print("\n*** Enter -1 at any time to quit ***") print("\nEnter the upper limit (≥ 0) for the Catalan number sequence: ", end="") try: while True: N = int(input().strip()) if N < 0: print("\n********* Goodbye!! ************") break else: print(f"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print("Try another upper limit for the sequence: ", end="") except (NameError, ValueError): print("\n********* Invalid input, goodbye! ************\n") import doctest doctest.testmod()
!usrbinenv python3 LeetCdoe No.70: Climbing Stairs Distinct ways to climb a numberofsteps staircase where each time you can either climb 1 or 2 steps. Args: numberofsteps: number of steps on the staircase Returns: Distinct ways to climb a numberofsteps staircase Raises: AssertionError: numberofsteps not positive integer climbstairs3 3 climbstairs1 1 climbstairs7 doctest: ELLIPSIS Traceback most recent call last: ... AssertionError: numberofsteps needs to be positive integer, your input 7
#!/usr/bin/env python3 def climb_stairs(number_of_steps: int) -> int: """ LeetCdoe No.70: Climbing Stairs Distinct ways to climb a number_of_steps staircase where each time you can either climb 1 or 2 steps. Args: number_of_steps: number of steps on the staircase Returns: Distinct ways to climb a number_of_steps staircase Raises: AssertionError: number_of_steps not positive integer >>> climb_stairs(3) 3 >>> climb_stairs(1) 1 >>> climb_stairs(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: number_of_steps needs to be positive integer, your input -7 """ assert ( isinstance(number_of_steps, int) and number_of_steps > 0 ), f"number_of_steps needs to be positive integer, your input {number_of_steps}" if number_of_steps == 1: return 1 previous, current = 1, 1 for _ in range(number_of_steps - 1): current, previous = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
Question: You are given an array of distinct integers and you have to tell how many different ways of selecting the elements from the array are there such that the sum of chosen elements is equal to the target number tar. Example Input: N 3 target 5 array 1, 2, 5 Output: 9 Approach: The basic idea is to go over recursively to find the way such that the sum of chosen elements is tar. For every element, we have two choices 1. Include the element in our set of chosen elements. 2. Dont include the element in our set of chosen elements. Function checks the all possible combinations, and returns the count of possible combination in exponential Time Complexity. combinationsumiv3, 1,2,5, 5 9 Function checks the all possible combinations, and returns the count of possible combination in ON2 Time Complexity as we are using Dynamic programming array here. combinationsumivdparray3, 1,2,5, 5 9 Function checks the all possible combinations with using bottom up approach, and returns the count of possible combination in ON2 Time Complexity as we are using Dynamic programming array here. combinationsumivbottomup3, 1,2,5, 5 9
def combination_sum_iv(n: int, array: list[int], target: int) -> int: """ Function checks the all possible combinations, and returns the count of possible combination in exponential Time Complexity. >>> combination_sum_iv(3, [1,2,5], 5) 9 """ def count_of_possible_combinations(target: int) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item) for item in array) return count_of_possible_combinations(target) def combination_sum_iv_dp_array(n: int, array: list[int], target: int) -> int: """ Function checks the all possible combinations, and returns the count of possible combination in O(N^2) Time Complexity as we are using Dynamic programming array here. >>> combination_sum_iv_dp_array(3, [1,2,5], 5) 9 """ def count_of_possible_combinations_with_dp_array( target: int, dp_array: list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] answer = sum( count_of_possible_combinations_with_dp_array(target - item, dp_array) for item in array ) dp_array[target] = answer return answer dp_array = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(target, dp_array) def combination_sum_iv_bottom_up(n: int, array: list[int], target: int) -> int: """ Function checks the all possible combinations with using bottom up approach, and returns the count of possible combination in O(N^2) Time Complexity as we are using Dynamic programming array here. >>> combination_sum_iv_bottom_up(3, [1,2,5], 5) 9 """ dp_array = [0] * (target + 1) dp_array[0] = 1 for i in range(1, target + 1): for j in range(n): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() n = 3 target = 5 array = [1, 2, 5] print(combination_sum_iv(n, array, target))
Author : Turfa Auliarachman Date : October 12, 2016 This is a pure Python implementation of Dynamic Programming solution to the edit distance problem. The problem is : Given two strings A and B. Find the minimum number of operations to string B such that A B. The permitted operations are removal, insertion, and substitution. Use : solver EditDistance editDistanceResult solver.solvefirstString, secondString EditDistance.mindisttopdownintention, execution 5 EditDistance.mindisttopdownintention, 9 EditDistance.mindisttopdown, 0 EditDistance.mindistbottomupintention, execution 5 EditDistance.mindistbottomupintention, 9 EditDistance.mindistbottomup, 0
class EditDistance: """ Use : solver = EditDistance() editDistanceResult = solver.solve(firstString, secondString) """ def __init__(self): self.word1 = "" self.word2 = "" self.dp = [] def __min_dist_top_down_dp(self, m: int, n: int) -> int: if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.word1[m] == self.word2[n]: self.dp[m][n] = self.__min_dist_top_down_dp(m - 1, n - 1) else: insert = self.__min_dist_top_down_dp(m, n - 1) delete = self.__min_dist_top_down_dp(m - 1, n) replace = self.__min_dist_top_down_dp(m - 1, n - 1) self.dp[m][n] = 1 + min(insert, delete, replace) return self.dp[m][n] def min_dist_top_down(self, word1: str, word2: str) -> int: """ >>> EditDistance().min_dist_top_down("intention", "execution") 5 >>> EditDistance().min_dist_top_down("intention", "") 9 >>> EditDistance().min_dist_top_down("", "") 0 """ self.word1 = word1 self.word2 = word2 self.dp = [[-1 for _ in range(len(word2))] for _ in range(len(word1))] return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1) def min_dist_bottom_up(self, word1: str, word2: str) -> int: """ >>> EditDistance().min_dist_bottom_up("intention", "execution") 5 >>> EditDistance().min_dist_bottom_up("intention", "") 9 >>> EditDistance().min_dist_bottom_up("", "") 0 """ self.word1 = word1 self.word2 = word2 m = len(word1) n = len(word2) self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0: # first string is empty self.dp[i][j] = j elif j == 0: # second string is empty self.dp[i][j] = i elif word1[i - 1] == word2[j - 1]: # last characters are equal self.dp[i][j] = self.dp[i - 1][j - 1] else: insert = self.dp[i][j - 1] delete = self.dp[i - 1][j] replace = self.dp[i - 1][j - 1] self.dp[i][j] = 1 + min(insert, delete, replace) return self.dp[m][n] if __name__ == "__main__": solver = EditDistance() print("****************** Testing Edit Distance DP Algorithm ******************") print() S1 = input("Enter the first string: ").strip() S2 = input("Enter the second string: ").strip() print() print(f"The minimum edit distance is: {solver.min_dist_top_down(S1, S2)}") print(f"The minimum edit distance is: {solver.min_dist_bottom_up(S1, S2)}") print() print("*************** End of Testing Edit Distance DP Algorithm ***************")
Factorial of a number using memoization factorial7 5040 factorial1 Traceback most recent call last: ... ValueError: Number should not be negative. factoriali for i in range10 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880
# Factorial of a number using memoization from functools import lru_cache @lru_cache def factorial(num: int) -> int: """ >>> factorial(7) 5040 >>> factorial(-1) Traceback (most recent call last): ... ValueError: Number should not be negative. >>> [factorial(i) for i in range(10)] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] """ if num < 0: raise ValueError("Number should not be negative.") return 1 if num in (0, 1) else num * factorial(num - 1) if __name__ == "__main__": import doctest doctest.testmod()
!usrbinenv python3 This program calculates the nth Fibonacci number in Ologn. It's possible to calculate F1000000 in less than a second. return Fn fibonaccii for i in range13 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 returns Fn, Fn1 F2n Fn2Fn1 Fn F2n1 Fn12Fn2
#!/usr/bin/env python3 """ This program calculates the nth Fibonacci number in O(log(n)). It's possible to calculate F(1_000_000) in less than a second. """ from __future__ import annotations import sys def fibonacci(n: int) -> int: """ return F(n) >>> [fibonacci(i) for i in range(13)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] """ if n < 0: raise ValueError("Negative arguments are not supported") return _fib(n)[0] # returns (F(n), F(n-1)) def _fib(n: int) -> tuple[int, int]: if n == 0: # (F(0), F(1)) return (0, 1) # F(2n) = F(n)[2F(n+1) − F(n)] # F(2n+1) = F(n+1)^2+F(n)^2 a, b = _fib(n // 2) c = a * (b * 2 - a) d = a * a + b * b return (d, c + d) if n % 2 else (c, d) if __name__ == "__main__": n = int(sys.argv[1]) print(f"fibonacci({n}) is {fibonacci(n)}")
This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem. Get the Fibonacci number of index. If the number does not exist, calculate all missing numbers leading up to the number of index. Fibonacci.get10 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 Fibonacci.get5 0, 1, 1, 2, 3
class Fibonacci: def __init__(self) -> None: self.sequence = [0, 1] def get(self, index: int) -> list: """ Get the Fibonacci number of `index`. If the number does not exist, calculate all missing numbers leading up to the number of `index`. >>> Fibonacci().get(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] >>> Fibonacci().get(5) [0, 1, 1, 2, 3] """ if (difference := index - (len(self.sequence) - 2)) >= 1: for _ in range(difference): self.sequence.append(self.sequence[-1] + self.sequence[-2]) return self.sequence[:index] def main() -> None: print( "Fibonacci Series Using Dynamic Programming\n", "Enter the index of the Fibonacci number you want to calculate ", "in the prompt below. (To exit enter exit or Ctrl-C)\n", sep="", ) fibonacci = Fibonacci() while True: prompt: str = input(">> ") if prompt in {"exit", "quit"}: break try: index: int = int(prompt) except ValueError: print("Enter a number or 'exit'") continue print(fibonacci.get(index)) if __name__ == "__main__": main()
https:en.wikipedia.orgwikiFizzbuzzProgramming Plays FizzBuzz. Prints Fizz if number is a multiple of 3. Prints Buzz if its a multiple of 5. Prints FizzBuzz if its a multiple of both 3 and 5 or 15. Else Prints The Number Itself. fizzbuzz1,7 '1 2 Fizz 4 Buzz Fizz 7 ' fizzbuzz1,0 Traceback most recent call last: ... ValueError: Iterations must be done more than 0 times to play FizzBuzz fizzbuzz5,5 Traceback most recent call last: ... ValueError: starting number must be and integer and be more than 0 fizzbuzz10,5 Traceback most recent call last: ... ValueError: Iterations must be done more than 0 times to play FizzBuzz fizzbuzz1.5,5 Traceback most recent call last: ... ValueError: starting number must be and integer and be more than 0 fizzbuzz1,5.5 Traceback most recent call last: ... ValueError: iterations must be defined as integers starting number must be and integer and be more than 0 if not iterations 1: raise ValueErrorIterations must be done more than 0 times to play FizzBuzz out while number iterations: if number 3 0: out Fizz if number 5 0: out Buzz if 0 not in number 3, number 5: out strnumber printout number 1 out return out if name main: import doctest doctest.testmod
# https://en.wikipedia.org/wiki/Fizz_buzz#Programming def fizz_buzz(number: int, iterations: int) -> str: """ Plays FizzBuzz. Prints Fizz if number is a multiple of 3. Prints Buzz if its a multiple of 5. Prints FizzBuzz if its a multiple of both 3 and 5 or 15. Else Prints The Number Itself. >>> fizz_buzz(1,7) '1 2 Fizz 4 Buzz Fizz 7 ' >>> fizz_buzz(1,0) Traceback (most recent call last): ... ValueError: Iterations must be done more than 0 times to play FizzBuzz >>> fizz_buzz(-5,5) Traceback (most recent call last): ... ValueError: starting number must be and integer and be more than 0 >>> fizz_buzz(10,-5) Traceback (most recent call last): ... ValueError: Iterations must be done more than 0 times to play FizzBuzz >>> fizz_buzz(1.5,5) Traceback (most recent call last): ... ValueError: starting number must be and integer and be more than 0 >>> fizz_buzz(1,5.5) Traceback (most recent call last): ... ValueError: iterations must be defined as integers """ if not isinstance(iterations, int): raise ValueError("iterations must be defined as integers") if not isinstance(number, int) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz") out = "" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(number) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts plus the number of partitions into at least k1 parts. Subtracting 1 from each part of a partition of n into k parts gives a partition of nk into k parts. These two facts together are used for this algorithm. https:en.wikipedia.orgwikiPartitionnumbertheory https:en.wikipedia.orgwikiPartitionfunctionnumbertheory partition5 7 partition7 15 partition100 190569292 partition1000 24061467864032622473692149727991 partition7 Traceback most recent call last: ... IndexError: list index out of range partition0 Traceback most recent call last: ... IndexError: list assignment index out of range partition7.8 Traceback most recent call last: ... TypeError: 'float' object cannot be interpreted as an integer
def partition(m: int) -> int: """ >>> partition(5) 7 >>> partition(7) 15 >>> partition(100) 190569292 >>> partition(1_000) 24061467864032622473692149727991 >>> partition(-7) Traceback (most recent call last): ... IndexError: list index out of range >>> partition(0) Traceback (most recent call last): ... IndexError: list assignment index out of range >>> partition(7.8) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer """ memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: n = int(input("Enter a number: ").strip()) print(partition(n)) except ValueError: print("Please enter a number.") else: try: n = int(sys.argv[1]) print(partition(n)) except ValueError: print("Please pass a number.")
Author : Syed Faizan 3rd Year Student IIIT Pune github : faizan2700 You are given a bitmask m and you want to efficiently iterate through all of its submasks. The mask s is submask of m if only bits that were included in bitmask are set Args: mask : number which shows mask always integer 0, zero does not have any submasks Returns: allsubmasks : the list of submasks of mask mask s is called submask of mask m if only bits that were included in original mask are set Raises: AssertionError: mask not positive integer listofsubmasks15 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 listofsubmasks13 13, 12, 9, 8, 5, 4, 1 listofsubmasks7 doctest: ELLIPSIS Traceback most recent call last: ... AssertionError: mask needs to be positive integer, your input 7 listofsubmasks0 doctest: ELLIPSIS Traceback most recent call last: ... AssertionError: mask needs to be positive integer, your input 0 first submask iterated will be mask itself then operation will be performed to get other submasks till we reach empty submask that is zero zero is not included in final submasks list
from __future__ import annotations def list_of_submasks(mask: int) -> list[int]: """ Args: mask : number which shows mask ( always integer > 0, zero does not have any submasks ) Returns: all_submasks : the list of submasks of mask (mask s is called submask of mask m if only bits that were included in original mask are set Raises: AssertionError: mask not positive integer >>> list_of_submasks(15) [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] >>> list_of_submasks(13) [13, 12, 9, 8, 5, 4, 1] >>> list_of_submasks(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: mask needs to be positive integer, your input -7 >>> list_of_submasks(0) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: mask needs to be positive integer, your input 0 """ assert ( isinstance(mask, int) and mask > 0 ), f"mask needs to be positive integer, your input {mask}" """ first submask iterated will be mask itself then operation will be performed to get other submasks till we reach empty submask that is zero ( zero is not included in final submasks list ) """ all_submasks = [] submask = mask while submask: all_submasks.append(submask) submask = (submask - 1) & mask return all_submasks if __name__ == "__main__": import doctest doctest.testmod()
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that only the integer weights 01 knapsack problem is solvable using dynamic programming. This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with 1s filled up Solves the integer weights knapsack problem returns one of the several possible optimal subsets. Parameters W: int, the total maximum weight for the given knapsack problem. wt: list, the vector of weights for all items where wti is the weight of the ith item. val: list, the vector of values for all items where vali is the value of the ith item Returns optimalval: float, the optimal value for the given knapsack problem exampleoptionalset: set, the indices of one of the optimal subsets which gave rise to the optimal value. Examples knapsackwithexamplesolution10, 1, 3, 5, 2, 10, 20, 100, 22 142, 2, 3, 4 knapsackwithexamplesolution6, 4, 3, 2, 3, 3, 2, 4, 4 8, 3, 4 knapsackwithexamplesolution6, 4, 3, 2, 3, 3, 2, 4 Traceback most recent call last: ... ValueError: The number of weights must be the same as the number of values. But got 4 weights and 3 values Recursively reconstructs one of the optimal subsets given a filled DP table and the vector of weights Parameters dp: list of list, the table of a solved integer weight dynamic programming problem wt: list or tuple, the vector of weights of the items i: int, the index of the item under consideration j: int, the current possible maximum weight optimalset: set, the optimal subset so far. This gets modified by the function. Returns None for the current item i at a maximum weight j to be part of an optimal subset, the optimal value at i, j must be greater than the optimal value at i1, j. where i 1 means considering only the previous items at the given maximum weight Adding test case for knapsack testing the dynamic programming problem with example the optimal subset for the above example are items 3 and 4
def mf_knapsack(i, wt, val, j): """ This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up """ global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: val = mf_knapsack(i - 1, wt, val, j) else: val = max( mf_knapsack(i - 1, wt, val, j), mf_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1], ) f[i][j] = val return f[i][j] def knapsack(w, wt, val, n): dp = [[0] * (w + 1) for _ in range(n + 1)] for i in range(1, n + 1): for w_ in range(1, w + 1): if wt[i - 1] <= w_: dp[i][w_] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]], dp[i - 1][w_]) else: dp[i][w_] = dp[i - 1][w_] return dp[n][w_], dp def knapsack_with_example_solution(w: int, wt: list, val: list): """ Solves the integer weights knapsack problem returns one of the several possible optimal subsets. Parameters --------- W: int, the total maximum weight for the given knapsack problem. wt: list, the vector of weights for all items where wt[i] is the weight of the i-th item. val: list, the vector of values for all items where val[i] is the value of the i-th item Returns ------- optimal_val: float, the optimal value for the given knapsack problem example_optional_set: set, the indices of one of the optimal subsets which gave rise to the optimal value. Examples ------- >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22]) (142, {2, 3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4]) (8, {3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4]) Traceback (most recent call last): ... ValueError: The number of weights must be the same as the number of values. But got 4 weights and 3 values """ if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) num_items = len(wt) if num_items != len(val): msg = ( "The number of weights must be the same as the number of values.\n" f"But got {num_items} weights and {len(val)} values" ) raise ValueError(msg) for i in range(num_items): if not isinstance(wt[i], int): msg = ( "All weights must be integers but got weight of " f"type {type(wt[i])} at index {i}" ) raise TypeError(msg) optimal_val, dp_table = knapsack(w, wt, val, num_items) example_optional_set: set = set() _construct_solution(dp_table, wt, num_items, w, example_optional_set) return optimal_val, example_optional_set def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): """ Recursively reconstructs one of the optimal subsets given a filled DP table and the vector of weights Parameters --------- dp: list of list, the table of a solved integer weight dynamic programming problem wt: list or tuple, the vector of weights of the items i: int, the index of the item under consideration j: int, the current possible maximum weight optimal_set: set, the optimal subset so far. This gets modified by the function. Returns ------- None """ # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(dp, wt, i - 1, j, optimal_set) else: optimal_set.add(i) _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set) if __name__ == "__main__": """ Adding test case for knapsack """ val = [3, 2, 4, 4] wt = [4, 3, 2, 3] n = 4 w = 6 f = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] optimal_solution, _ = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
Algorithm to find the biggest subset in the given array such that for any 2 elements x and y in the subset, either x divides y or y divides x. largestdivisiblesubset1, 16, 7, 8, 4 16, 8, 4, 1 largestdivisiblesubset1, 2, 3 2, 1 largestdivisiblesubset1, 2, 3 3 largestdivisiblesubset1, 2, 4, 8 8, 4, 2, 1 largestdivisiblesubset1, 2, 4, 8 8, 4, 2, 1 largestdivisiblesubset1, 1, 1 1, 1, 1 largestdivisiblesubset0, 0, 0 0, 0, 0 largestdivisiblesubset1, 1, 1 1, 1, 1 largestdivisiblesubset Sort the array in ascending order as the sequence does not matter we only have to pick up a subset. Initialize memo with 1s and hash with increasing numbers Iterate through the array Find the maximum length and its corresponding index Reconstruct the divisible subset
from __future__ import annotations def largest_divisible_subset(items: list[int]) -> list[int]: """ Algorithm to find the biggest subset in the given array such that for any 2 elements x and y in the subset, either x divides y or y divides x. >>> largest_divisible_subset([1, 16, 7, 8, 4]) [16, 8, 4, 1] >>> largest_divisible_subset([1, 2, 3]) [2, 1] >>> largest_divisible_subset([-1, -2, -3]) [-3] >>> largest_divisible_subset([1, 2, 4, 8]) [8, 4, 2, 1] >>> largest_divisible_subset((1, 2, 4, 8)) [8, 4, 2, 1] >>> largest_divisible_subset([1, 1, 1]) [1, 1, 1] >>> largest_divisible_subset([0, 0, 0]) [0, 0, 0] >>> largest_divisible_subset([-1, -1, -1]) [-1, -1, -1] >>> largest_divisible_subset([]) [] """ # Sort the array in ascending order as the sequence does not matter we only have to # pick up a subset. items = sorted(items) number_of_items = len(items) # Initialize memo with 1s and hash with increasing numbers memo = [1] * number_of_items hash_array = list(range(number_of_items)) # Iterate through the array for i, item in enumerate(items): for prev_index in range(i): if ((items[prev_index] != 0 and item % items[prev_index]) == 0) and ( (1 + memo[prev_index]) > memo[i] ): memo[i] = 1 + memo[prev_index] hash_array[i] = prev_index ans = -1 last_index = -1 # Find the maximum length and its corresponding index for i, memo_item in enumerate(memo): if memo_item > ans: ans = memo_item last_index = i # Reconstruct the divisible subset if last_index == -1: return [] result = [items[last_index]] while hash_array[last_index] != last_index: last_index = hash_array[last_index] result.append(items[last_index]) return result if __name__ == "__main__": from doctest import testmod testmod() items = [1, 16, 7, 8, 4] print( f"The longest divisible subset of {items} is {largest_divisible_subset(items)}." )
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily continuous. Example:abc, abg are subsequences of abcdefgh. Finds the longest common subsequence between two strings. Also returns the The subsequence found Parameters x: str, one of the strings y: str, the other string Returns Lmn: int, the length of the longest subsequence. Also equal to lenseq Seq: str, the subsequence found longestcommonsubsequenceprogramming, gaming 6, 'gaming' longestcommonsubsequencephysics, smartphone 2, 'ph' longestcommonsubsequencecomputer, food 1, 'o' find the length of strings declaring the array for storing the dp values
def longest_common_subsequence(x: str, y: str): """ Finds the longest common subsequence between two strings. Also returns the The subsequence found Parameters ---------- x: str, one of the strings y: str, the other string Returns ------- L[m][n]: int, the length of the longest subsequence. Also equal to len(seq) Seq: str, the subsequence found >>> longest_common_subsequence("programming", "gaming") (6, 'gaming') >>> longest_common_subsequence("physics", "smartphone") (2, 'ph') >>> longest_common_subsequence("computer", "food") (1, 'o') """ # find the length of strings assert x is not None assert y is not None m = len(x) n = len(y) # declaring the array for storing the dp values l = [[0] * (n + 1) for _ in range(m + 1)] # noqa: E741 for i in range(1, m + 1): for j in range(1, n + 1): match = 1 if x[i - 1] == y[j - 1] else 0 l[i][j] = max(l[i - 1][j], l[i][j - 1], l[i - 1][j - 1] + match) seq = "" i, j = m, n while i > 0 and j > 0: match = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: seq = x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": a = "AGGTAB" b = "GXTXAYB" expected_ln = 4 expected_subseq = "GTAB" ln, subseq = longest_common_subsequence(a, b) print("len =", ln, ", sub-sequence =", subseq) import doctest doctest.testmod()
Longest Common Substring Problem Statement: Given two sequences, find the longest common substring present in both of them. A substring is necessarily continuous. Example: abcdef and xabded have two longest common substrings, ab or de. Therefore, algorithm should return any one of them. Finds the longest common substring between two strings. longestcommonsubstring, '' longestcommonsubstringa, '' longestcommonsubstring, a '' longestcommonsubstringa, a 'a' longestcommonsubstringabcdef, bcd 'bcd' longestcommonsubstringabcdef, xabded 'ab' longestcommonsubstringGeeksforGeeks, GeeksQuiz 'Geeks' longestcommonsubstringabcdxyz, xyzabcd 'abcd' longestcommonsubstringzxabcdezy, yzabcdezx 'abcdez' longestcommonsubstringOldSite:GeeksforGeeks.org, NewSite:GeeksQuiz.com 'Site:Geeks' longestcommonsubstring1, 1 Traceback most recent call last: ... ValueError: longestcommonsubstring takes two strings for inputs
def longest_common_substring(text1: str, text2: str) -> str: """ Finds the longest common substring between two strings. >>> longest_common_substring("", "") '' >>> longest_common_substring("a","") '' >>> longest_common_substring("", "a") '' >>> longest_common_substring("a", "a") 'a' >>> longest_common_substring("abcdef", "bcd") 'bcd' >>> longest_common_substring("abcdef", "xabded") 'ab' >>> longest_common_substring("GeeksforGeeks", "GeeksQuiz") 'Geeks' >>> longest_common_substring("abcdxyz", "xyzabcd") 'abcd' >>> longest_common_substring("zxabcdezy", "yzabcdezx") 'abcdez' >>> longest_common_substring("OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com") 'Site:Geeks' >>> longest_common_substring(1, 1) Traceback (most recent call last): ... ValueError: longest_common_substring() takes two strings for inputs """ if not (isinstance(text1, str) and isinstance(text2, str)): raise ValueError("longest_common_substring() takes two strings for inputs") text1_length = len(text1) text2_length = len(text2) dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)] ans_index = 0 ans_length = 0 for i in range(1, text1_length + 1): for j in range(1, text2_length + 1): if text1[i - 1] == text2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: ans_index = i ans_length = dp[i][j] return text1[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
Author : Mehdi ALAOUI This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence. The problem is : Given an array, to find the longest and increasing subarray in that given array and return it. Example: 10, 22, 9, 33, 21, 50, 41, 60, 80 as input will return 10, 22, 33, 41, 60, 80 as output Some examples longestsubsequence10, 22, 9, 33, 21, 50, 41, 60, 80 10, 22, 33, 41, 60, 80 longestsubsequence4, 8, 7, 5, 1, 12, 2, 3, 9 1, 2, 3, 9 longestsubsequence9, 8, 7, 6, 5, 7 8 longestsubsequence1, 1, 1 1, 1, 1 longestsubsequence If the array contains only one element, we return it it's the stop condition of recursion Else
from __future__ import annotations def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive """ Some examples >>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) [10, 22, 33, 41, 60, 80] >>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9]) [1, 2, 3, 9] >>> longest_subsequence([9, 8, 7, 6, 5, 7]) [8] >>> longest_subsequence([1, 1, 1]) [1, 1, 1] >>> longest_subsequence([]) [] """ array_length = len(array) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else pivot = array[0] is_found = False i = 1 longest_subseq: list[int] = [] while not is_found and i < array_length: if array[i] < pivot: is_found = True temp_array = [element for element in array[i:] if element >= array[i]] temp_array = longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): longest_subseq = temp_array else: i += 1 temp_array = [element for element in array[1:] if element >= pivot] temp_array = [pivot, *longest_subsequence(temp_array)] if len(temp_array) > len(longest_subseq): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
Author: Aravind Kashyap File: lis.py comments: This programme outputs the Longest Strictly Increasing Subsequence in ONLogN Where N is the Number of elements in the list longestincreasingsubsequencelength2, 5, 3, 7, 11, 8, 10, 13, 6 6 longestincreasingsubsequencelength 0 longestincreasingsubsequencelength0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, ... 3, 11, 7, 15 6 longestincreasingsubsequencelength5, 4, 3, 2, 1 1
############################# # Author: Aravind Kashyap # File: lis.py # comments: This programme outputs the Longest Strictly Increasing Subsequence in # O(NLogN) Where N is the Number of elements in the list ############################# from __future__ import annotations def ceil_index(v, l, r, key): # noqa: E741 while r - l > 1: m = (l + r) // 2 if v[m] >= key: r = m else: l = m # noqa: E741 return r def longest_increasing_subsequence_length(v: list[int]) -> int: """ >>> longest_increasing_subsequence_length([2, 5, 3, 7, 11, 8, 10, 13, 6]) 6 >>> longest_increasing_subsequence_length([]) 0 >>> longest_increasing_subsequence_length([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, ... 3, 11, 7, 15]) 6 >>> longest_increasing_subsequence_length([5, 4, 3, 2, 1]) 1 """ if len(v) == 0: return 0 tail = [0] * len(v) length = 1 tail[0] = v[0] for i in range(1, len(v)): if v[i] < tail[0]: tail[0] = v[i] elif v[i] > tail[length - 1]: tail[length] = v[i] length += 1 else: tail[ceil_index(tail, -1, length - 1, v[i])] = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
author: Sanket Kittad Given a string s, find the longest palindromic subsequence's length in s. Input: s bbbab Output: 4 Explanation: One possible longest palindromic subsequence is bbbb. Leetcode link: https:leetcode.comproblemslongestpalindromicsubsequencedescription This function returns the longest palindromic subsequence in a string longestpalindromicsubsequencebbbab 4 longestpalindromicsubsequencebbabcbcab 7 create and initialise dp array If characters at i and j are the same include them in the palindromic subsequence
def longest_palindromic_subsequence(input_string: str) -> int: """ This function returns the longest palindromic subsequence in a string >>> longest_palindromic_subsequence("bbbab") 4 >>> longest_palindromic_subsequence("bbabcbcab") 7 """ n = len(input_string) rev = input_string[::-1] m = len(rev) dp = [[-1] * (m + 1) for i in range(n + 1)] for i in range(n + 1): dp[i][0] = 0 for i in range(m + 1): dp[0][i] = 0 # create and initialise dp array for i in range(1, n + 1): for j in range(1, m + 1): # If characters at i and j are the same # include them in the palindromic subsequence if input_string[i - 1] == rev[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
Find the minimum number of multiplications needed to multiply chain of matrices. Reference: https:www.geeksforgeeks.orgmatrixchainmultiplicationdp8 The algorithm has interesting realworld applications. Example: 1. Image transformations in Computer Graphics as images are composed of matrix. 2. Solve complex polynomial equations in the field of algebra using least processing power. 3. Calculate overall impact of macroeconomic decisions as economic equations involve a number of variables. 4. Selfdriving car navigation can be made more accurate as matrix multiplication can accurately determine position and orientation of obstacles in short time. Python doctests can be run with the following command: python m doctest v matrixchainmultiply.py Given a sequence arr that represents chain of 2D matrices such that the dimension of the ith matrix is arri1arri. So suppose arr 40, 20, 30, 10, 30 means we have 4 matrices of dimensions 4020, 2030, 3010 and 1030. matrixchainmultiply returns an integer denoting minimum number of multiplications to multiply the chain. We do not need to perform actual multiplication here. We only need to decide the order in which to perform the multiplication. Hints: 1. Number of multiplications ie cost to multiply 2 matrices of size mp and pn is mpn. 2. Cost of matrix multiplication is associative ie M1M2M3 ! M1M2M3 3. Matrix multiplication is not commutative. So, M1M2 does not mean M2M1 can be done. 4. To determine the required order, we can try different combinations. So, this problem has overlapping subproblems and can be solved using recursion. We use Dynamic Programming for optimal time complexity. Example input: arr 40, 20, 30, 10, 30 output: 26000 Find the minimum number of multiplcations required to multiply the chain of matrices Args: arr: The input array of integers. Returns: Minimum number of multiplications needed to multiply the chain Examples: matrixchainmultiply1, 2, 3, 4, 3 30 matrixchainmultiply10 0 matrixchainmultiply10, 20 0 matrixchainmultiply19, 2, 19 722 matrixchainmultiplylistrange1, 100 323398 matrixchainmultiplylistrange1, 251 2626798 initialising 2D dp matrix we want minimum cost of multiplication of matrices of dimension ik and kj. This cost is arri1arrkarrj. Source: https:en.wikipedia.orgwikiMatrixchainmultiplication The dynamic programming solution is faster than cached the recursive solution and can handle larger inputs. matrixchainorder1, 2, 3, 4, 3 30 matrixchainorder10 0 matrixchainorder10, 20 0 matrixchainorder19, 2, 19 722 matrixchainorderlistrange1, 100 323398 matrixchainorderlistrange1, 251 Max before RecursionError is raised 2626798 printfStarting: msg
from collections.abc import Iterator from contextlib import contextmanager from functools import cache from sys import maxsize def matrix_chain_multiply(arr: list[int]) -> int: """ Find the minimum number of multiplcations required to multiply the chain of matrices Args: arr: The input array of integers. Returns: Minimum number of multiplications needed to multiply the chain Examples: >>> matrix_chain_multiply([1, 2, 3, 4, 3]) 30 >>> matrix_chain_multiply([10]) 0 >>> matrix_chain_multiply([10, 20]) 0 >>> matrix_chain_multiply([19, 2, 19]) 722 >>> matrix_chain_multiply(list(range(1, 100))) 323398 # >>> matrix_chain_multiply(list(range(1, 251))) # 2626798 """ if len(arr) < 2: return 0 # initialising 2D dp matrix n = len(arr) dp = [[maxsize for j in range(n)] for i in range(n)] # we want minimum cost of multiplication of matrices # of dimension (i*k) and (k*j). This cost is arr[i-1]*arr[k]*arr[j]. for i in range(n - 1, 0, -1): for j in range(i, n): if i == j: dp[i][j] = 0 continue for k in range(i, j): dp[i][j] = min( dp[i][j], dp[i][k] + dp[k + 1][j] + arr[i - 1] * arr[k] * arr[j] ) return dp[1][n - 1] def matrix_chain_order(dims: list[int]) -> int: """ Source: https://en.wikipedia.org/wiki/Matrix_chain_multiplication The dynamic programming solution is faster than cached the recursive solution and can handle larger inputs. >>> matrix_chain_order([1, 2, 3, 4, 3]) 30 >>> matrix_chain_order([10]) 0 >>> matrix_chain_order([10, 20]) 0 >>> matrix_chain_order([19, 2, 19]) 722 >>> matrix_chain_order(list(range(1, 100))) 323398 # >>> matrix_chain_order(list(range(1, 251))) # Max before RecursionError is raised # 2626798 """ @cache def a(i: int, j: int) -> int: return min( (a(i, k) + dims[i] * dims[k] * dims[j] + a(k, j) for k in range(i + 1, j)), default=0, ) return a(0, len(dims) - 1) @contextmanager def elapsed_time(msg: str) -> Iterator: # print(f"Starting: {msg}") from time import perf_counter_ns start = perf_counter_ns() yield print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10 ** 9} seconds.") if __name__ == "__main__": import doctest doctest.testmod() with elapsed_time("matrix_chain_order"): print(f"{matrix_chain_order(list(range(1, 251))) = }") with elapsed_time("matrix_chain_multiply"): print(f"{matrix_chain_multiply(list(range(1, 251))) = }") with elapsed_time("matrix_chain_order"): print(f"{matrix_chain_order(list(range(1, 251))) = }") with elapsed_time("matrix_chain_multiply"): print(f"{matrix_chain_multiply(list(range(1, 251))) = }")
Dynamic Programming Implementation of Matrix Chain Multiplication Time Complexity: On3 Space Complexity: On2 Print order of matrix with Ai as Matrix Size of matrix created from above array will be 3035 3515 155 510 1020 2025
import sys """ Dynamic Programming Implementation of Matrix Chain Multiplication Time Complexity: O(n^3) Space Complexity: O(n^2) """ def matrix_chain_order(array): n = len(array) matrix = [[0 for x in range(n)] for x in range(n)] sol = [[0 for x in range(n)] for x in range(n)] for chain_length in range(2, n): for a in range(1, n - chain_length + 1): b = a + chain_length - 1 matrix[a][b] = sys.maxsize for c in range(a, b): cost = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: matrix[a][b] = cost sol[a][b] = c return matrix, sol # Print order of matrix with Ai as Matrix def print_optiomal_solution(optimal_solution, i, j): if i == j: print("A" + str(i), end=" ") else: print("(", end=" ") print_optiomal_solution(optimal_solution, i, optimal_solution[i][j]) print_optiomal_solution(optimal_solution, optimal_solution[i][j] + 1, j) print(")", end=" ") def main(): array = [30, 35, 15, 5, 10, 20, 25] n = len(array) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 matrix, optimal_solution = matrix_chain_order(array) print("No. of Operation required: " + str(matrix[1][n - 1])) print_optiomal_solution(optimal_solution, 1, n - 1) if __name__ == "__main__": main()
Video Explanation: https:www.youtube.comwatch?v6w60Zi1NtL8featureemblogo Find the maximum nonadjacent sum of the integers in the nums input list maximumnonadjacentsum1, 2, 3 4 maximumnonadjacentsum1, 5, 3, 7, 2, 2, 6 18 maximumnonadjacentsum1, 5, 3, 7, 2, 2, 6 0 maximumnonadjacentsum499, 500, 3, 7, 2, 2, 6 500
# Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo from __future__ import annotations def maximum_non_adjacent_sum(nums: list[int]) -> int: """ Find the maximum non-adjacent sum of the integers in the nums input list >>> maximum_non_adjacent_sum([1, 2, 3]) 4 >>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6]) 18 >>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6]) 0 >>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6]) 500 """ if not nums: return 0 max_including = nums[0] max_excluding = 0 for num in nums[1:]: max_including, max_excluding = ( max_excluding + num, max(max_including, max_excluding), ) return max(max_excluding, max_including) if __name__ == "__main__": import doctest doctest.testmod()
Returns the maximum product that can be obtained by multiplying a contiguous subarray of the given integer list nums. Example: maxproductsubarray2, 3, 2, 4 6 maxproductsubarray2, 0, 1 0 maxproductsubarray2, 3, 2, 4, 1 48 maxproductsubarray1 1 maxproductsubarray0 0 maxproductsubarray 0 maxproductsubarray 0 maxproductsubarrayNone 0 maxproductsubarray2, 3, 2, 4.5, 1 Traceback most recent call last: ... ValueError: numbers must be an iterable of integers maxproductsubarrayABC Traceback most recent call last: ... ValueError: numbers must be an iterable of integers update the maximum and minimum subarray products update the maximum product found till now
def max_product_subarray(numbers: list[int]) -> int: """ Returns the maximum product that can be obtained by multiplying a contiguous subarray of the given integer list `nums`. Example: >>> max_product_subarray([2, 3, -2, 4]) 6 >>> max_product_subarray((-2, 0, -1)) 0 >>> max_product_subarray([2, 3, -2, 4, -1]) 48 >>> max_product_subarray([-1]) -1 >>> max_product_subarray([0]) 0 >>> max_product_subarray([]) 0 >>> max_product_subarray("") 0 >>> max_product_subarray(None) 0 >>> max_product_subarray([2, 3, -2, 4.5, -1]) Traceback (most recent call last): ... ValueError: numbers must be an iterable of integers >>> max_product_subarray("ABC") Traceback (most recent call last): ... ValueError: numbers must be an iterable of integers """ if not numbers: return 0 if not isinstance(numbers, (list, tuple)) or not all( isinstance(number, int) for number in numbers ): raise ValueError("numbers must be an iterable of integers") max_till_now = min_till_now = max_prod = numbers[0] for i in range(1, len(numbers)): # update the maximum and minimum subarray products number = numbers[i] if number < 0: max_till_now, min_till_now = min_till_now, max_till_now max_till_now = max(number, max_till_now * number) min_till_now = min(number, min_till_now * number) # update the maximum product found till now max_prod = max(max_prod, max_till_now) return max_prod
The maximum subarray sum problem is the task of finding the maximum sum that can be obtained from a contiguous subarray within a given array of numbers. For example, given the array 2, 1, 3, 4, 1, 2, 1, 5, 4, the contiguous subarray with the maximum sum is 4, 1, 2, 1, so the maximum subarray sum is 6. Kadane's algorithm is a simple dynamic programming algorithm that solves the maximum subarray sum problem in On time and O1 space. Reference: https:en.wikipedia.orgwikiMaximumsubarrayproblem Solves the maximum subarray sum problem using Kadane's algorithm. :param arr: the given array of numbers :param allowemptysubarrays: if True, then the algorithm considers empty subarrays maxsubarraysum2, 8, 9 19 maxsubarraysum0, 0 0 maxsubarraysum1.0, 0.0, 1.0 1.0 maxsubarraysum1, 2, 3, 4, 2 10 maxsubarraysum2, 1, 3, 4, 1, 2, 1, 5, 4 6 maxsubarraysum2, 3, 9, 8, 2 8 maxsubarraysum2, 3, 1, 4, 6 1 maxsubarraysum2, 3, 1, 4, 6, allowemptysubarraysTrue 0 maxsubarraysum 0
from collections.abc import Sequence def max_subarray_sum( arr: Sequence[float], allow_empty_subarrays: bool = False ) -> float: """ Solves the maximum subarray sum problem using Kadane's algorithm. :param arr: the given array of numbers :param allow_empty_subarrays: if True, then the algorithm considers empty subarrays >>> max_subarray_sum([2, 8, 9]) 19 >>> max_subarray_sum([0, 0]) 0 >>> max_subarray_sum([-1.0, 0.0, 1.0]) 1.0 >>> max_subarray_sum([1, 2, 3, 4, -2]) 10 >>> max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]) 6 >>> max_subarray_sum([2, 3, -9, 8, -2]) 8 >>> max_subarray_sum([-2, -3, -1, -4, -6]) -1 >>> max_subarray_sum([-2, -3, -1, -4, -6], allow_empty_subarrays=True) 0 >>> max_subarray_sum([]) 0 """ if not arr: return 0 max_sum = 0 if allow_empty_subarrays else float("-inf") curr_sum = 0.0 for num in arr: curr_sum = max(0 if allow_empty_subarrays else num, curr_sum + num) max_sum = max(max_sum, curr_sum) return max_sum if __name__ == "__main__": from doctest import testmod testmod() nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"{max_subarray_sum(nums) = }")
Author : Alexander Pantyukhin Date : October 14, 2022 This is an implementation of the upbottom approach to find edit distance. The implementation was tested on Leetcode: https:leetcode.comproblemseditdistance Levinstein distance Dynamic Programming: up down. mindistanceupbottomintention, execution 5 mindistanceupbottomintention, 9 mindistanceupbottom, 0 mindistanceupbottomzooicoarchaeologist, zoologist 10 if first word index overflows delete all from the second word if second word index overflows delete all from the first word
import functools def min_distance_up_bottom(word1: str, word2: str) -> int: """ >>> min_distance_up_bottom("intention", "execution") 5 >>> min_distance_up_bottom("intention", "") 9 >>> min_distance_up_bottom("", "") 0 >>> min_distance_up_bottom("zooicoarchaeologist", "zoologist") 10 """ len_word1 = len(word1) len_word2 = len(word2) @functools.cache def min_distance(index1: int, index2: int) -> int: # if first word index overflows - delete all from the second word if index1 >= len_word1: return len_word2 - index2 # if second word index overflows - delete all from the first word if index2 >= len_word2: return len_word1 - index1 diff = int(word1[index1] != word2[index2]) # current letters not identical return min( 1 + min_distance(index1 + 1, index2), 1 + min_distance(index1, index2 + 1), diff + min_distance(index1 + 1, index2 + 1), ) return min_distance(0, 0) if __name__ == "__main__": import doctest doctest.testmod()
You have m types of coins available in infinite quantities where the value of each coins is given in the array SS0,... Sm1 Can you determine number of ways of making change for n units using the given types of coins? https:www.hackerrank.comchallengescoinchangeproblem dpcount1, 2, 3, 4 4 dpcount1, 2, 3, 7 8 dpcount2, 5, 3, 6, 10 5 dpcount10, 99 0 dpcount4, 5, 6, 0 1 dpcount1, 2, 3, 5 0 tablei represents the number of ways to get to amount i There is exactly 1 way to get to zeroYou pick no coins. Pick all coins one by one and update table values after the index greater than or equal to the value of the picked coin
def dp_count(s, n): """ >>> dp_count([1, 2, 3], 4) 4 >>> dp_count([1, 2, 3], 7) 8 >>> dp_count([2, 5, 3, 6], 10) 5 >>> dp_count([10], 99) 0 >>> dp_count([4, 5, 6], 0) 1 >>> dp_count([1, 2, 3], -5) 0 """ if n < 0: return 0 # table[i] represents the number of ways to get to amount i table = [0] * (n + 1) # There is exactly 1 way to get to zero(You pick no coins). table[0] = 1 # Pick all coins one by one and update table[] values # after the index greater than or equal to the value of the # picked coin for coin_val in s: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
Youtube Explanation: https:www.youtube.comwatch?vlBRtnuxggU Find the minimum cost traced by all possible paths from top left to bottom right in a given matrix minimumcostpath2, 1, 3, 1, 4, 2 6 minimumcostpath2, 1, 4, 2, 1, 3, 3, 2, 1 7 preprocessing the first row preprocessing the first column updating the path cost for current position
# Youtube Explanation: https://www.youtube.com/watch?v=lBRtnuxg-gU from __future__ import annotations def minimum_cost_path(matrix: list[list[int]]) -> int: """ Find the minimum cost traced by all possible paths from top left to bottom right in a given matrix >>> minimum_cost_path([[2, 1], [3, 1], [4, 2]]) 6 >>> minimum_cost_path([[2, 1, 4], [2, 1, 3], [3, 2, 1]]) 7 """ # preprocessing the first row for i in range(1, len(matrix[0])): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(matrix)): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1]) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
Partition a set into two subsets such that the difference of subset sums is minimum findmin1, 2, 3, 4, 5 1 findmin5, 5, 5, 5, 5 5 findmin5, 5, 5, 5 0 findmin3 3 findmin 0 findmin1, 2, 3, 4 0 findmin0, 0, 0, 0 0 findmin1, 5, 5, 1 0 findmin1, 5, 5, 1 0 findmin9, 9, 9, 9, 9 9 findmin1, 5, 10, 3 1 findmin1, 0, 1 0 findminrange10, 0, 1 1 findmin1 Traceback most recent call last: IndexError: list assignment index out of range findmin0, 0, 0, 1, 2, 4 Traceback most recent call last: ... IndexError: list assignment index out of range findmin1, 5, 10, 3 Traceback most recent call last: ... IndexError: list assignment index out of range
def find_min(numbers: list[int]) -> int: """ >>> find_min([1, 2, 3, 4, 5]) 1 >>> find_min([5, 5, 5, 5, 5]) 5 >>> find_min([5, 5, 5, 5]) 0 >>> find_min([3]) 3 >>> find_min([]) 0 >>> find_min([1, 2, 3, 4]) 0 >>> find_min([0, 0, 0, 0]) 0 >>> find_min([-1, -5, 5, 1]) 0 >>> find_min([-1, -5, 5, 1]) 0 >>> find_min([9, 9, 9, 9, 9]) 9 >>> find_min([1, 5, 10, 3]) 1 >>> find_min([-1, 0, 1]) 0 >>> find_min(range(10, 0, -1)) 1 >>> find_min([-1]) Traceback (most recent call last): -- IndexError: list assignment index out of range >>> find_min([0, 0, 0, 1, 2, -4]) Traceback (most recent call last): ... IndexError: list assignment index out of range >>> find_min([-1, -5, -10, -3]) Traceback (most recent call last): ... IndexError: list assignment index out of range """ n = len(numbers) s = sum(numbers) dp = [[False for x in range(s + 1)] for y in range(n + 1)] for i in range(n + 1): dp[i][0] = True for i in range(1, s + 1): dp[0][i] = False for i in range(1, n + 1): for j in range(1, s + 1): dp[i][j] = dp[i - 1][j] if numbers[i - 1] <= j: dp[i][j] = dp[i][j] or dp[i - 1][j - numbers[i - 1]] for j in range(int(s / 2), -1, -1): if dp[n][j] is True: diff = s - 2 * j break return diff if __name__ == "__main__": from doctest import testmod testmod()
Return the length of the shortest contiguous subarray in a list of numbers whose sum is at least target. Reference: https:stackoverflow.comquestions8269916 minimumsubarraysum7, 2, 3, 1, 2, 4, 3 2 minimumsubarraysum7, 2, 3, 1, 2, 4, 3 4 minimumsubarraysum11, 1, 1, 1, 1, 1, 1, 1, 1 0 minimumsubarraysum10, 1, 2, 3, 4, 5, 6, 7 2 minimumsubarraysum5, 1, 1, 1, 1, 1, 5 1 minimumsubarraysum0, 0 minimumsubarraysum0, 1, 2, 3 1 minimumsubarraysum10, 10, 20, 30 1 minimumsubarraysum7, 1, 1, 1, 1, 1, 1, 10 1 minimumsubarraysum6, 0 minimumsubarraysum2, 1, 2, 3 1 minimumsubarraysum6, 0 minimumsubarraysum6, 3, 4, 5 1 minimumsubarraysum8, None 0 minimumsubarraysum2, ABC Traceback most recent call last: ... ValueError: numbers must be an iterable of integers
import sys def minimum_subarray_sum(target: int, numbers: list[int]) -> int: """ Return the length of the shortest contiguous subarray in a list of numbers whose sum is at least target. Reference: https://stackoverflow.com/questions/8269916 >>> minimum_subarray_sum(7, [2, 3, 1, 2, 4, 3]) 2 >>> minimum_subarray_sum(7, [2, 3, -1, 2, 4, -3]) 4 >>> minimum_subarray_sum(11, [1, 1, 1, 1, 1, 1, 1, 1]) 0 >>> minimum_subarray_sum(10, [1, 2, 3, 4, 5, 6, 7]) 2 >>> minimum_subarray_sum(5, [1, 1, 1, 1, 1, 5]) 1 >>> minimum_subarray_sum(0, []) 0 >>> minimum_subarray_sum(0, [1, 2, 3]) 1 >>> minimum_subarray_sum(10, [10, 20, 30]) 1 >>> minimum_subarray_sum(7, [1, 1, 1, 1, 1, 1, 10]) 1 >>> minimum_subarray_sum(6, []) 0 >>> minimum_subarray_sum(2, [1, 2, 3]) 1 >>> minimum_subarray_sum(-6, []) 0 >>> minimum_subarray_sum(-6, [3, 4, 5]) 1 >>> minimum_subarray_sum(8, None) 0 >>> minimum_subarray_sum(2, "ABC") Traceback (most recent call last): ... ValueError: numbers must be an iterable of integers """ if not numbers: return 0 if target == 0 and target in numbers: return 0 if not isinstance(numbers, (list, tuple)) or not all( isinstance(number, int) for number in numbers ): raise ValueError("numbers must be an iterable of integers") left = right = curr_sum = 0 min_len = sys.maxsize while right < len(numbers): curr_sum += numbers[right] while curr_sum >= target and left <= right: min_len = min(min_len, right - left + 1) curr_sum -= numbers[left] left += 1 right += 1 return 0 if min_len == sys.maxsize else min_len
Count the number of minimum squares to represent a number minimumsquarestorepresentanumber25 1 minimumsquarestorepresentanumber37 2 minimumsquarestorepresentanumber21 3 minimumsquarestorepresentanumber58 2 minimumsquarestorepresentanumber1 Traceback most recent call last: ... ValueError: the value of input must not be a negative number minimumsquarestorepresentanumber0 1 minimumsquarestorepresentanumber12.34 Traceback most recent call last: ... ValueError: the value of input must be a natural number
import math import sys def minimum_squares_to_represent_a_number(number: int) -> int: """ Count the number of minimum squares to represent a number >>> minimum_squares_to_represent_a_number(25) 1 >>> minimum_squares_to_represent_a_number(37) 2 >>> minimum_squares_to_represent_a_number(21) 3 >>> minimum_squares_to_represent_a_number(58) 2 >>> minimum_squares_to_represent_a_number(-1) Traceback (most recent call last): ... ValueError: the value of input must not be a negative number >>> minimum_squares_to_represent_a_number(0) 1 >>> minimum_squares_to_represent_a_number(12.34) Traceback (most recent call last): ... ValueError: the value of input must be a natural number """ if number != int(number): raise ValueError("the value of input must be a natural number") if number < 0: raise ValueError("the value of input must not be a negative number") if number == 0: return 1 answers = [-1] * (number + 1) answers[0] = 0 for i in range(1, number + 1): answer = sys.maxsize root = int(math.sqrt(i)) for j in range(1, root + 1): current_answer = 1 + answers[i - (j**2)] answer = min(answer, current_answer) answers[i] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
YouTube Explanation: https:www.youtube.comwatch?vf2xi3c1S95M Given an integer n, return the minimum steps from n to 1 AVAILABLE STEPS: Decrement by 1 if n is divisible by 2, divide by 2 if n is divisible by 3, divide by 3 Example 1: n 10 10 9 3 1 Result: 3 steps Example 2: n 15 15 5 4 2 1 Result: 4 steps Example 3: n 6 6 2 1 Result: 2 step Minimum steps to 1 implemented using tabulation. minstepstoone10 3 minstepstoone15 4 minstepstoone6 2 :param number: :return int: starting position check if out of bounds check if out of bounds
from __future__ import annotations __author__ = "Alexander Joslin" def min_steps_to_one(number: int) -> int: """ Minimum steps to 1 implemented using tabulation. >>> min_steps_to_one(10) 3 >>> min_steps_to_one(15) 4 >>> min_steps_to_one(6) 2 :param number: :return int: """ if number <= 0: msg = f"n must be greater than 0. Got n = {number}" raise ValueError(msg) table = [number + 1] * (number + 1) # starting position table[1] = 0 for i in range(1, number): table[i + 1] = min(table[i + 1], table[i] + 1) # check if out of bounds if i * 2 <= number: table[i * 2] = min(table[i * 2], table[i] + 1) # check if out of bounds if i * 3 <= number: table[i * 3] = min(table[i * 3], table[i] + 1) return table[number] if __name__ == "__main__": import doctest doctest.testmod()
Author : Alexander Pantyukhin Date : November 1, 2022 Task: Given a list of days when you need to travel. Each day is integer from 1 to 365. You are able to use tickets for 1 day, 7 days and 30 days. Each ticket has a cost. Find the minimum cost you need to travel every day in the given list of days. Implementation notes: implementation Dynamic Programming up bottom approach. Runtime complexity: On The implementation was tested on the leetcode: https:leetcode.comproblemsminimumcostfortickets Minimum Cost For Tickets Dynamic Programming: up down. mincosttickets1, 4, 6, 7, 8, 20, 2, 7, 15 11 mincosttickets1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 2, 7, 15 17 mincosttickets1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 2, 90, 150 24 mincosttickets2, 2, 90, 150 2 mincosttickets, 2, 90, 150 0 mincosttickets'hello', 2, 90, 150 Traceback most recent call last: ... ValueError: The parameter days should be a list of integers mincosttickets, 'world' Traceback most recent call last: ... ValueError: The parameter costs should be a list of three integers mincosttickets0.25, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 2, 90, 150 Traceback most recent call last: ... ValueError: The parameter days should be a list of integers mincosttickets1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 2, 0.9, 150 Traceback most recent call last: ... ValueError: The parameter costs should be a list of three integers mincosttickets1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 2, 90, 150 Traceback most recent call last: ... ValueError: All days elements should be greater than 0 mincosttickets2, 367, 2, 90, 150 Traceback most recent call last: ... ValueError: All days elements should be less than 366 mincosttickets2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, Traceback most recent call last: ... ValueError: The parameter costs should be a list of three integers mincosttickets, Traceback most recent call last: ... ValueError: The parameter costs should be a list of three integers mincosttickets2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 1, 2, 3, 4 Traceback most recent call last: ... ValueError: The parameter costs should be a list of three integers Validation
import functools def mincost_tickets(days: list[int], costs: list[int]) -> int: """ >>> mincost_tickets([1, 4, 6, 7, 8, 20], [2, 7, 15]) 11 >>> mincost_tickets([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 7, 15]) 17 >>> mincost_tickets([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 90, 150]) 24 >>> mincost_tickets([2], [2, 90, 150]) 2 >>> mincost_tickets([], [2, 90, 150]) 0 >>> mincost_tickets('hello', [2, 90, 150]) Traceback (most recent call last): ... ValueError: The parameter days should be a list of integers >>> mincost_tickets([], 'world') Traceback (most recent call last): ... ValueError: The parameter costs should be a list of three integers >>> mincost_tickets([0.25, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 90, 150]) Traceback (most recent call last): ... ValueError: The parameter days should be a list of integers >>> mincost_tickets([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 0.9, 150]) Traceback (most recent call last): ... ValueError: The parameter costs should be a list of three integers >>> mincost_tickets([-1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 90, 150]) Traceback (most recent call last): ... ValueError: All days elements should be greater than 0 >>> mincost_tickets([2, 367], [2, 90, 150]) Traceback (most recent call last): ... ValueError: All days elements should be less than 366 >>> mincost_tickets([2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], []) Traceback (most recent call last): ... ValueError: The parameter costs should be a list of three integers >>> mincost_tickets([], []) Traceback (most recent call last): ... ValueError: The parameter costs should be a list of three integers >>> mincost_tickets([2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [1, 2, 3, 4]) Traceback (most recent call last): ... ValueError: The parameter costs should be a list of three integers """ # Validation if not isinstance(days, list) or not all(isinstance(day, int) for day in days): raise ValueError("The parameter days should be a list of integers") if len(costs) != 3 or not all(isinstance(cost, int) for cost in costs): raise ValueError("The parameter costs should be a list of three integers") if len(days) == 0: return 0 if min(days) <= 0: raise ValueError("All days elements should be greater than 0") if max(days) >= 366: raise ValueError("All days elements should be less than 366") days_set = set(days) @functools.cache def dynamic_programming(index: int) -> int: if index > 365: return 0 if index not in days_set: return dynamic_programming(index + 1) return min( costs[0] + dynamic_programming(index + 1), costs[1] + dynamic_programming(index + 7), costs[2] + dynamic_programming(index + 30), ) return dynamic_programming(1) if __name__ == "__main__": import doctest doctest.testmod()
!usrbinenv python3 This Python program implements an optimal binary search tree abbreviated BST building dynamic programming algorithm that delivers On2 performance. The goal of the optimal BST problem is to build a lowcost BST for a given set of nodes, each with its own key and frequency. The frequency of the node is defined as how many time the node is being searched. The search cost of binary search tree is given by this formula: cost1, n sumi 1 to ndepthnodei 1 nodeifreq where n is number of nodes in the BST. The characteristic of lowcost BSTs is having a faster overall search time than other implementations. The reason for their fast search time is that the nodes with high frequencies will be placed near the root of the tree while the nodes with low frequencies will be placed near the leaves of the tree thus reducing search time in the most frequent instances. Binary Search Tree Node def initself, key, freq: self.key key self.freq freq def strself: return fNodekeyself.key, freqself.freq def printbinarysearchtreeroot, key, i, j, parent, isleft: if i j or i 0 or j lenroot 1: return node rootij if parent 1: root does not have a parent printfkeynode is the root of the binary search tree. elif isleft: printfkeynode is the left child of key parent. else: printfkeynode is the right child of key parent. printbinarysearchtreeroot, key, i, node 1, keynode, True printbinarysearchtreeroot, key, node 1, j, keynode, False def findoptimalbinarysearchtreenodes: Tree nodes must be sorted first, the code below sorts the keys in increasing order and rearrange its frequencies accordingly. nodes.sortkeylambda node: node.key n lennodes keys nodesi.key for i in rangen freqs nodesi.freq for i in rangen This 2D array stores the overall tree cost which's as minimized as possible; for a single key, cost is equal to frequency of the key. dp freqsi if i j else 0 for j in rangen for i in rangen sumij stores the sum of key frequencies between i and j inclusive in nodes array total freqsi if i j else 0 for j in rangen for i in rangen stores tree roots that will be used later for constructing binary search tree root i if i j else 0 for j in rangen for i in rangen for intervallength in range2, n 1: for i in rangen intervallength 1: j i intervallength 1 dpij sys.maxsize set the value to infinity totalij totalij 1 freqsj Apply Knuth's optimization Loop without optimization: for r in rangei, j 1: for r in rangerootij 1, rooti 1j 1: r is a temporal root left dpir 1 if r ! i else 0 optimal cost for left subtree right dpr 1j if r ! j else 0 optimal cost for right subtree cost left totalij right if dpij cost: dpij cost rootij r printBinary search tree nodes: for node in nodes: printnode printfnThe cost of optimal BST for given tree nodes is dp0n 1. printbinarysearchtreeroot, keys, 0, n 1, 1, False def main: A sample binary search tree nodes Nodei, randint1, 50 for i in range10, 0, 1 findoptimalbinarysearchtreenodes if name main: main
#!/usr/bin/env python3 # This Python program implements an optimal binary search tree (abbreviated BST) # building dynamic programming algorithm that delivers O(n^2) performance. # # The goal of the optimal BST problem is to build a low-cost BST for a # given set of nodes, each with its own key and frequency. The frequency # of the node is defined as how many time the node is being searched. # The search cost of binary search tree is given by this formula: # # cost(1, n) = sum{i = 1 to n}((depth(node_i) + 1) * node_i_freq) # # where n is number of nodes in the BST. The characteristic of low-cost # BSTs is having a faster overall search time than other implementations. # The reason for their fast search time is that the nodes with high # frequencies will be placed near the root of the tree while the nodes # with low frequencies will be placed near the leaves of the tree thus # reducing search time in the most frequent instances. import sys from random import randint class Node: """Binary Search Tree Node""" def __init__(self, key, freq): self.key = key self.freq = freq def __str__(self): """ >>> str(Node(1, 2)) 'Node(key=1, freq=2)' """ return f"Node(key={self.key}, freq={self.freq})" def print_binary_search_tree(root, key, i, j, parent, is_left): """ Recursive function to print a BST from a root table. >>> key = [3, 8, 9, 10, 17, 21] >>> root = [[0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 3], [0, 0, 2, 3, 3, 3], \ [0, 0, 0, 3, 3, 3], [0, 0, 0, 0, 4, 5], [0, 0, 0, 0, 0, 5]] >>> print_binary_search_tree(root, key, 0, 5, -1, False) 8 is the root of the binary search tree. 3 is the left child of key 8. 10 is the right child of key 8. 9 is the left child of key 10. 21 is the right child of key 10. 17 is the left child of key 21. """ if i > j or i < 0 or j > len(root) - 1: return node = root[i][j] if parent == -1: # root does not have a parent print(f"{key[node]} is the root of the binary search tree.") elif is_left: print(f"{key[node]} is the left child of key {parent}.") else: print(f"{key[node]} is the right child of key {parent}.") print_binary_search_tree(root, key, i, node - 1, key[node], True) print_binary_search_tree(root, key, node + 1, j, key[node], False) def find_optimal_binary_search_tree(nodes): """ This function calculates and prints the optimal binary search tree. The dynamic programming algorithm below runs in O(n^2) time. Implemented from CLRS (Introduction to Algorithms) book. https://en.wikipedia.org/wiki/Introduction_to_Algorithms >>> find_optimal_binary_search_tree([Node(12, 8), Node(10, 34), Node(20, 50), \ Node(42, 3), Node(25, 40), Node(37, 30)]) Binary search tree nodes: Node(key=10, freq=34) Node(key=12, freq=8) Node(key=20, freq=50) Node(key=25, freq=40) Node(key=37, freq=30) Node(key=42, freq=3) <BLANKLINE> The cost of optimal BST for given tree nodes is 324. 20 is the root of the binary search tree. 10 is the left child of key 20. 12 is the right child of key 10. 25 is the right child of key 20. 37 is the right child of key 25. 42 is the right child of key 37. """ # Tree nodes must be sorted first, the code below sorts the keys in # increasing order and rearrange its frequencies accordingly. nodes.sort(key=lambda node: node.key) n = len(nodes) keys = [nodes[i].key for i in range(n)] freqs = [nodes[i].freq for i in range(n)] # This 2D array stores the overall tree cost (which's as minimized as possible); # for a single key, cost is equal to frequency of the key. dp = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # sum[i][j] stores the sum of key frequencies between i and j inclusive in nodes # array total = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # stores tree roots that will be used later for constructing binary search tree root = [[i if i == j else 0 for j in range(n)] for i in range(n)] for interval_length in range(2, n + 1): for i in range(n - interval_length + 1): j = i + interval_length - 1 dp[i][j] = sys.maxsize # set the value to "infinity" total[i][j] = total[i][j - 1] + freqs[j] # Apply Knuth's optimization # Loop without optimization: for r in range(i, j + 1): for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree cost = left + total[i][j] + right if dp[i][j] > cost: dp[i][j] = cost root[i][j] = r print("Binary search tree nodes:") for node in nodes: print(node) print(f"\nThe cost of optimal BST for given tree nodes is {dp[0][n - 1]}.") print_binary_search_tree(root, keys, 0, n - 1, -1, False) def main(): # A sample binary search tree nodes = [Node(i, randint(1, 50)) for i in range(10, 0, -1)] find_optimal_binary_search_tree(nodes) if __name__ == "__main__": main()
Given a string s, partition s such that every substring of the partition is a palindrome. Find the minimum cuts needed for a palindrome partitioning of s. Time Complexity: On2 Space Complexity: On2 For other explanations refer to: https:www.youtube.comwatch?vH8V5hJUGd0 Returns the minimum cuts needed for a palindrome partitioning of string findminimumpartitionsaab 1 findminimumpartitionsaaa 0 findminimumpartitionsababbbabbababa 3
def find_minimum_partitions(string: str) -> int: """ Returns the minimum cuts needed for a palindrome partitioning of string >>> find_minimum_partitions("aab") 1 >>> find_minimum_partitions("aaa") 0 >>> find_minimum_partitions("ababbbabbababa") 3 """ length = len(string) cut = [0] * length is_palindromic = [[False for i in range(length)] for j in range(length)] for i, c in enumerate(string): mincut = i for j in range(i + 1): if c == string[j] and (i - j < 2 or is_palindromic[j + 1][i - 1]): is_palindromic[j][i] = True mincut = min(mincut, 0 if j == 0 else (cut[j - 1] + 1)) cut[i] = mincut return cut[length - 1] if __name__ == "__main__": s = input("Enter the string: ").strip() ans = find_minimum_partitions(s) print(f"Minimum number of partitions required for the '{s}' is {ans}")
Regex matching check if a text matches pattern or not. Pattern: '.' Matches any single character. '' Matches zero or more of the preceding element. More info: https:medium.comtricktheinterviwerregularexpressionmatching9972eb74c03 Recursive matching algorithm. Time complexity: O2 text pattern Space complexity: Recursion depth is Otext pattern. :param text: Text to match. :param pattern: Pattern to match. :return: True if text matches pattern, False otherwise. recursivematch'abc', 'a.c' True recursivematch'abc', 'af.c' True recursivematch'abc', 'a.c' True recursivematch'abc', 'a.cd' False recursivematch'aa', '.' True Dynamic programming matching algorithm. Time complexity: Otext pattern Space complexity: Otext pattern :param text: Text to match. :param pattern: Pattern to match. :return: True if text matches pattern, False otherwise. dpmatch'abc', 'a.c' True dpmatch'abc', 'af.c' True dpmatch'abc', 'a.c' True dpmatch'abc', 'a.cd' False dpmatch'aa', '.' True
def recursive_match(text: str, pattern: str) -> bool: """ Recursive matching algorithm. Time complexity: O(2 ^ (|text| + |pattern|)) Space complexity: Recursion depth is O(|text| + |pattern|). :param text: Text to match. :param pattern: Pattern to match. :return: True if text matches pattern, False otherwise. >>> recursive_match('abc', 'a.c') True >>> recursive_match('abc', 'af*.c') True >>> recursive_match('abc', 'a.c*') True >>> recursive_match('abc', 'a.c*d') False >>> recursive_match('aa', '.*') True """ if not pattern: return not text if not text: return pattern[-1] == "*" and recursive_match(text, pattern[:-2]) if text[-1] == pattern[-1] or pattern[-1] == ".": return recursive_match(text[:-1], pattern[:-1]) if pattern[-1] == "*": return recursive_match(text[:-1], pattern) or recursive_match( text, pattern[:-2] ) return False def dp_match(text: str, pattern: str) -> bool: """ Dynamic programming matching algorithm. Time complexity: O(|text| * |pattern|) Space complexity: O(|text| * |pattern|) :param text: Text to match. :param pattern: Pattern to match. :return: True if text matches pattern, False otherwise. >>> dp_match('abc', 'a.c') True >>> dp_match('abc', 'af*.c') True >>> dp_match('abc', 'a.c*') True >>> dp_match('abc', 'a.c*d') False >>> dp_match('aa', '.*') True """ m = len(text) n = len(pattern) dp = [[False for _ in range(n + 1)] for _ in range(m + 1)] dp[0][0] = True for j in range(1, n + 1): dp[0][j] = pattern[j - 1] == "*" and dp[0][j - 2] for i in range(1, m + 1): for j in range(1, n + 1): if pattern[j - 1] in {".", text[i - 1]}: dp[i][j] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": dp[i][j] = dp[i][j - 2] if pattern[j - 2] in {".", text[i - 1]}: dp[i][j] |= dp[i - 1][j] else: dp[i][j] = False return dp[m][n] if __name__ == "__main__": import doctest doctest.testmod()
This module provides two implementations for the rodcutting problem: 1. A naive recursive implementation which has an exponential runtime 2. Two dynamic programming implementations which have quadratic runtime The rodcutting problem is the problem of finding the maximum possible revenue obtainable from a rod of length n given a list of prices for each integral piece of the rod. The maximum revenue can thus be obtained by cutting the rod and selling the pieces separately or not cutting it at all if the price of it is the maximum obtainable. Solves the rodcutting problem via naively without using the benefit of dynamic programming. The results is the same subproblems are solved several times leading to an exponential runtime Runtime: O2n Arguments n: int, the length of the rod prices: list, the prices for each piece of rod. pii is the price for a rod of length i Returns The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples naivecutrodrecursive4, 1, 5, 8, 9 10 naivecutrodrecursive10, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 30 Constructs a topdown dynamic programming solution for the rodcutting problem via memoization. This function serves as a wrapper for topdowncutrodrecursive Runtime: On2 Arguments n: int, the length of the rod prices: list, the prices for each piece of rod. pii is the price for a rod of length i Note For convenience and because Python's lists using 0indexing, lengthmaxrev n 1, to accommodate for the revenue obtainable from a rod of length 0. Returns The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples topdowncutrod4, 1, 5, 8, 9 10 topdowncutrod10, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 30 Constructs a topdown dynamic programming solution for the rodcutting problem via memoization. Runtime: On2 Arguments n: int, the length of the rod prices: list, the prices for each piece of rod. pii is the price for a rod of length i maxrev: list, the computed maximum revenue for a piece of rod. maxrevi is the maximum revenue obtainable for a rod of length i Returns The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Constructs a bottomup dynamic programming solution for the rodcutting problem Runtime: On2 Arguments n: int, the maximum length of the rod. prices: list, the prices for each piece of rod. pii is the price for a rod of length i Returns The maximum revenue obtainable from cutting a rod of length n given the prices for each piece of rod p. Examples bottomupcutrod4, 1, 5, 8, 9 10 bottomupcutrod10, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 30 lengthmaxrev n 1, to accommodate for the revenue obtainable from a rod of length 0. Basic checks on the arguments to the rodcutting algorithms n: int, the length of the rod prices: list, the price list for each piece of rod. Throws ValueError: if n is negative or there are fewer items in the price list than the length of the rod the best revenue comes from cutting the rod into 6 pieces, each of length 1 resulting in a revenue of 6 6 36.
def naive_cut_rod_recursive(n: int, prices: list): """ Solves the rod-cutting problem via naively without using the benefit of dynamic programming. The results is the same sub-problems are solved several times leading to an exponential runtime Runtime: O(2^n) Arguments ------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples -------- >>> naive_cut_rod_recursive(4, [1, 5, 8, 9]) 10 >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) if n == 0: return 0 max_revue = float("-inf") for i in range(1, n + 1): max_revue = max( max_revue, prices[i - 1] + naive_cut_rod_recursive(n - i, prices) ) return max_revue def top_down_cut_rod(n: int, prices: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. This function serves as a wrapper for _top_down_cut_rod_recursive Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Note ---- For convenience and because Python's lists using 0-indexing, length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of length 0. Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples ------- >>> top_down_cut_rod(4, [1, 5, 8, 9]) 10 >>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] return _top_down_cut_rod_recursive(n, prices, max_rev) def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` max_rev: list, the computed maximum revenue for a piece of rod. ``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. """ if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: max_revenue = float("-inf") for i in range(1, n + 1): max_revenue = max( max_revenue, prices[i - 1] + _top_down_cut_rod_recursive(n - i, prices, max_rev), ) max_rev[n] = max_revenue return max_rev[n] def bottom_up_cut_rod(n: int, prices: list): """ Constructs a bottom-up dynamic programming solution for the rod-cutting problem Runtime: O(n^2) Arguments ---------- n: int, the maximum length of the rod. prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable from cutting a rod of length n given the prices for each piece of rod p. Examples ------- >>> bottom_up_cut_rod(4, [1, 5, 8, 9]) 10 >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. max_rev = [float("-inf") for _ in range(n + 1)] max_rev[0] = 0 for i in range(1, n + 1): max_revenue_i = max_rev[i] for j in range(1, i + 1): max_revenue_i = max(max_revenue_i, prices[j - 1] + max_rev[i - j]) max_rev[i] = max_revenue_i return max_rev[n] def _enforce_args(n: int, prices: list): """ Basic checks on the arguments to the rod-cutting algorithms n: int, the length of the rod prices: list, the price list for each piece of rod. Throws ValueError: if n is negative or there are fewer items in the price list than the length of the rod """ if n < 0: msg = f"n must be greater than or equal to 0. Got n = {n}" raise ValueError(msg) if n > len(prices): msg = ( "Each integral piece of rod must have a corresponding price. " f"Got n = {n} but length of prices = {len(prices)}" ) raise ValueError(msg) def main(): prices = [6, 10, 12, 15, 20, 23] n = len(prices) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. expected_max_revenue = 36 max_rev_top_down = top_down_cut_rod(n, prices) max_rev_bottom_up = bottom_up_cut_rod(n, prices) max_rev_naive = naive_cut_rod_recursive(n, prices) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
https:en.wikipedia.orgwikiSmithE28093Watermanalgorithm The SmithWaterman algorithm is a dynamic programming algorithm used for sequence alignment. It is particularly useful for finding similarities between two sequences, such as DNA or protein sequences. In this implementation, gaps are penalized linearly, meaning that the score is reduced by a fixed amount for each gap introduced in the alignment. However, it's important to note that the SmithWaterman algorithm supports other gap penalty methods as well. Calculate the score for a character pair based on whether they match or mismatch. Returns 1 if the characters match, 1 if they mismatch, and 2 if either of the characters is a gap. scorefunction'A', 'A' 1 scorefunction'A', 'C' 1 scorefunction'', 'A' 2 scorefunction'A', '' 2 scorefunction'', '' 2 Perform the SmithWaterman local sequence alignment algorithm. Returns a 2D list representing the score matrix. Each value in the matrix corresponds to the score of the best local alignment ending at that point. smithwaterman'ACAC', 'CA' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'acac', 'ca' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'ACAC', 'ca' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'acac', 'CA' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'ACAC', '' 0, 0, 0, 0, 0 smithwaterman'', 'CA' 0, 0, 0 smithwaterman'ACAC', 'CA' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'acac', 'ca' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'ACAC', 'ca' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'acac', 'CA' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'ACAC', '' 0, 0, 0, 0, 0 smithwaterman'', 'CA' 0, 0, 0 smithwaterman'AGT', 'AGT' 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3 smithwaterman'AGT', 'GTA' 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 2, 0 smithwaterman'AGT', 'GTC' 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0 smithwaterman'AGT', 'G' 0, 0, 0, 0, 0, 1, 0, 0 smithwaterman'G', 'AGT' 0, 0, 0, 0, 0, 0, 1, 0 smithwaterman'AGT', 'AGTCT' 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 1, 1 smithwaterman'AGTCT', 'AGT' 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 1 smithwaterman'AGTCT', 'GTC' 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 1, 1 make both query and subject uppercase Initialize score matrix Calculate scores for each cell Take maximum score make both query and subject uppercase query query.upper subject subject.upper find the indices of the maximum value in the score matrix maxvalue floatinf imax jmax 0 for i, row in enumeratescore: for j, value in enumeraterow: if value maxvalue: maxvalue value imax, jmax i, j Traceback logic to find optimal alignment i imax j jmax align1 align2 gap scorefunction, guard against empty query or subject if i 0 or j 0: return while i 0 and j 0: if scoreij scorei 1j 1 scorefunction queryi 1, subjectj 1 : optimal path is a diagonal take both letters align1 queryi 1 align1 align2 subjectj 1 align2 i 1 j 1 elif scoreij scorei 1j gap: optimal path is a vertical align1 queryi 1 align1 align2 falign2 i 1 else: optimal path is a horizontal align1 falign1 align2 subjectj 1 align2 j 1 return falign1nalign2 if name main: query HEAGAWGHEE subject PAWHEAE score smithwatermanquery, subject, match1, mismatch1, gap2 printtracebackscore, query, subject
def score_function( source_char: str, target_char: str, match: int = 1, mismatch: int = -1, gap: int = -2, ) -> int: """ Calculate the score for a character pair based on whether they match or mismatch. Returns 1 if the characters match, -1 if they mismatch, and -2 if either of the characters is a gap. >>> score_function('A', 'A') 1 >>> score_function('A', 'C') -1 >>> score_function('-', 'A') -2 >>> score_function('A', '-') -2 >>> score_function('-', '-') -2 """ if "-" in (source_char, target_char): return gap return match if source_char == target_char else mismatch def smith_waterman( query: str, subject: str, match: int = 1, mismatch: int = -1, gap: int = -2, ) -> list[list[int]]: """ Perform the Smith-Waterman local sequence alignment algorithm. Returns a 2D list representing the score matrix. Each value in the matrix corresponds to the score of the best local alignment ending at that point. >>> smith_waterman('ACAC', 'CA') [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] >>> smith_waterman('acac', 'ca') [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] >>> smith_waterman('ACAC', 'ca') [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] >>> smith_waterman('acac', 'CA') [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] >>> smith_waterman('ACAC', '') [[0], [0], [0], [0], [0]] >>> smith_waterman('', 'CA') [[0, 0, 0]] >>> smith_waterman('ACAC', 'CA') [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] >>> smith_waterman('acac', 'ca') [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] >>> smith_waterman('ACAC', 'ca') [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] >>> smith_waterman('acac', 'CA') [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]] >>> smith_waterman('ACAC', '') [[0], [0], [0], [0], [0]] >>> smith_waterman('', 'CA') [[0, 0, 0]] >>> smith_waterman('AGT', 'AGT') [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]] >>> smith_waterman('AGT', 'GTA') [[0, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 2, 0]] >>> smith_waterman('AGT', 'GTC') [[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0]] >>> smith_waterman('AGT', 'G') [[0, 0], [0, 0], [0, 1], [0, 0]] >>> smith_waterman('G', 'AGT') [[0, 0, 0, 0], [0, 0, 1, 0]] >>> smith_waterman('AGT', 'AGTCT') [[0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 2, 0, 0, 0], [0, 0, 0, 3, 1, 1]] >>> smith_waterman('AGTCT', 'AGT') [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3], [0, 0, 0, 1], [0, 0, 0, 1]] >>> smith_waterman('AGTCT', 'GTC') [[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3], [0, 0, 1, 1]] """ # make both query and subject uppercase query = query.upper() subject = subject.upper() # Initialize score matrix m = len(query) n = len(subject) score = [[0] * (n + 1) for _ in range(m + 1)] kwargs = {"match": match, "mismatch": mismatch, "gap": gap} for i in range(1, m + 1): for j in range(1, n + 1): # Calculate scores for each cell match = score[i - 1][j - 1] + score_function( query[i - 1], subject[j - 1], **kwargs ) delete = score[i - 1][j] + gap insert = score[i][j - 1] + gap # Take maximum score score[i][j] = max(0, match, delete, insert) return score def traceback(score: list[list[int]], query: str, subject: str) -> str: r""" Perform traceback to find the optimal local alignment. Starts from the highest scoring cell in the matrix and traces back recursively until a 0 score is found. Returns the alignment strings. >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'ACAC', 'CA') 'CA\nCA' >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'acac', 'ca') 'CA\nCA' >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'ACAC', 'ca') 'CA\nCA' >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'acac', 'CA') 'CA\nCA' >>> traceback([[0, 0, 0]], 'ACAC', '') '' """ # make both query and subject uppercase query = query.upper() subject = subject.upper() # find the indices of the maximum value in the score matrix max_value = float("-inf") i_max = j_max = 0 for i, row in enumerate(score): for j, value in enumerate(row): if value > max_value: max_value = value i_max, j_max = i, j # Traceback logic to find optimal alignment i = i_max j = j_max align1 = "" align2 = "" gap = score_function("-", "-") # guard against empty query or subject if i == 0 or j == 0: return "" while i > 0 and j > 0: if score[i][j] == score[i - 1][j - 1] + score_function( query[i - 1], subject[j - 1] ): # optimal path is a diagonal take both letters align1 = query[i - 1] + align1 align2 = subject[j - 1] + align2 i -= 1 j -= 1 elif score[i][j] == score[i - 1][j] + gap: # optimal path is a vertical align1 = query[i - 1] + align1 align2 = f"-{align2}" i -= 1 else: # optimal path is a horizontal align1 = f"-{align1}" align2 = subject[j - 1] + align2 j -= 1 return f"{align1}\n{align2}" if __name__ == "__main__": query = "HEAGAWGHEE" subject = "PAWHEAE" score = smith_waterman(query, subject, match=1, mismatch=-1, gap=-2) print(traceback(score, query, subject))
Compute nelement combinations from a given list using dynamic programming. Args: elements: The list of elements from which combinations will be generated. n: The number of elements in each combination. Returns: A list of tuples, each representing a combination of n elements. subsetcombinationselements10, 20, 30, 40, n2 10, 20, 10, 30, 10, 40, 20, 30, 20, 40, 30, 40 subsetcombinationselements1, 2, 3, n1 1,, 2,, 3, subsetcombinationselements1, 2, 3, n3 1, 2, 3 subsetcombinationselements42, n1 42, subsetcombinationselements6, 7, 8, 9, n4 6, 7, 8, 9 subsetcombinationselements10, 20, 30, 40, 50, n0 subsetcombinationselements1, 2, 3, 4, n2 1, 2, 1, 3, 1, 4, 2, 3, 2, 4, 3, 4 subsetcombinationselements1, 'apple', 3.14, n2 1, 'apple', 1, 3.14, 'apple', 3.14 subsetcombinationselements'single', n0 subsetcombinationselements, n9 from itertools import combinations allsubsetcombinationsitems, n listcombinationsitems, n ... for items, n in ... 10, 20, 30, 40, 2, 1, 2, 3, 1, 1, 2, 3, 3, 42, 1, ... 6, 7, 8, 9, 4, 10, 20, 30, 40, 50, 1, 1, 2, 3, 4, 2, ... 1, 'apple', 3.14, 2, 'single', 0, , 9 True
def subset_combinations(elements: list[int], n: int) -> list: """ Compute n-element combinations from a given list using dynamic programming. Args: elements: The list of elements from which combinations will be generated. n: The number of elements in each combination. Returns: A list of tuples, each representing a combination of n elements. >>> subset_combinations(elements=[10, 20, 30, 40], n=2) [(10, 20), (10, 30), (10, 40), (20, 30), (20, 40), (30, 40)] >>> subset_combinations(elements=[1, 2, 3], n=1) [(1,), (2,), (3,)] >>> subset_combinations(elements=[1, 2, 3], n=3) [(1, 2, 3)] >>> subset_combinations(elements=[42], n=1) [(42,)] >>> subset_combinations(elements=[6, 7, 8, 9], n=4) [(6, 7, 8, 9)] >>> subset_combinations(elements=[10, 20, 30, 40, 50], n=0) [()] >>> subset_combinations(elements=[1, 2, 3, 4], n=2) [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] >>> subset_combinations(elements=[1, 'apple', 3.14], n=2) [(1, 'apple'), (1, 3.14), ('apple', 3.14)] >>> subset_combinations(elements=['single'], n=0) [()] >>> subset_combinations(elements=[], n=9) [] >>> from itertools import combinations >>> all(subset_combinations(items, n) == list(combinations(items, n)) ... for items, n in ( ... ([10, 20, 30, 40], 2), ([1, 2, 3], 1), ([1, 2, 3], 3), ([42], 1), ... ([6, 7, 8, 9], 4), ([10, 20, 30, 40, 50], 1), ([1, 2, 3, 4], 2), ... ([1, 'apple', 3.14], 2), (['single'], 0), ([], 9))) True """ r = len(elements) if n > r: return [] dp: list[list[tuple]] = [[] for _ in range(r + 1)] dp[0].append(()) for i in range(1, r + 1): for j in range(i, 0, -1): for prev_combination in dp[j - 1]: dp[j].append(tuple(prev_combination) + (elements[i - 1],)) try: return sorted(dp[n]) except TypeError: return dp[n] if __name__ == "__main__": from doctest import testmod testmod() print(f"{subset_combinations(elements=[10, 20, 30, 40], n=2) = }")
issumsubset2, 4, 6, 8, 5 False issumsubset2, 4, 6, 8, 14 True a subset value says 1 if that subset sum can be formed else 0 initially no subsets can be formed hence False0 for each arr value, a sum of zero0 can be formed by not taking any element hence True1 sum is not zero and set is empty then false
def is_sum_subset(arr: list[int], required_sum: int) -> bool: """ >>> is_sum_subset([2, 4, 6, 8], 5) False >>> is_sum_subset([2, 4, 6, 8], 14) True """ # a subset value says 1 if that subset sum can be formed else 0 # initially no subsets can be formed hence False/0 arr_len = len(arr) subset = [[False] * (required_sum + 1) for _ in range(arr_len + 1)] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1): subset[i][0] = True # sum is not zero and set is empty then false for i in range(1, required_sum + 1): subset[0][i] = False for i in range(1, arr_len + 1): for j in range(1, required_sum + 1): if arr[i - 1] > j: subset[i][j] = subset[i - 1][j] if arr[i - 1] <= j: subset[i][j] = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
Given an array of nonnegative integers representing an elevation map where the width of each bar is 1, this program calculates how much rainwater can be trapped. Example height 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 Output: 6 This problem can be solved using the concept of DYNAMIC PROGRAMMING. We calculate the maximum height of bars on the left and right of every bar in array. Then iterate over the width of structure and at each index. The amount of water that will be stored is equal to minimum of maximum height of bars on both sides minus height of bar at current position. The trappedrainwater function calculates the total amount of rainwater that can be trapped given an array of bar heights. It uses a dynamic programming approach, determining the maximum height of bars on both sides for each bar, and then computing the trapped water above each bar. The function returns the total trapped water. trappedrainwater0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 6 trappedrainwater7, 1, 5, 3, 6, 4 9 trappedrainwater7, 1, 5, 3, 6, 1 Traceback most recent call last: ... ValueError: No height can be negative
def trapped_rainwater(heights: tuple[int, ...]) -> int: """ The trapped_rainwater function calculates the total amount of rainwater that can be trapped given an array of bar heights. It uses a dynamic programming approach, determining the maximum height of bars on both sides for each bar, and then computing the trapped water above each bar. The function returns the total trapped water. >>> trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)) 6 >>> trapped_rainwater((7, 1, 5, 3, 6, 4)) 9 >>> trapped_rainwater((7, 1, 5, 3, 6, -1)) Traceback (most recent call last): ... ValueError: No height can be negative """ if not heights: return 0 if any(h < 0 for h in heights): raise ValueError("No height can be negative") length = len(heights) left_max = [0] * length left_max[0] = heights[0] for i, height in enumerate(heights[1:], start=1): left_max[i] = max(height, left_max[i - 1]) right_max = [0] * length right_max[-1] = heights[-1] for i in range(length - 2, -1, -1): right_max[i] = max(heights[i], right_max[i + 1]) return sum( min(left, right) - height for left, right, height in zip(left_max, right_max, heights) ) if __name__ == "__main__": import doctest doctest.testmod() print(f"{trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)) = }") print(f"{trapped_rainwater((7, 1, 5, 3, 6, 4)) = }")
Tribonacci sequence using Dynamic Programming Given a number, return first n Tribonacci Numbers. tribonacci5 0, 0, 1, 1, 2 tribonacci8 0, 0, 1, 1, 2, 4, 7, 13
# Tribonacci sequence using Dynamic Programming def tribonacci(num: int) -> list[int]: """ Given a number, return first n Tribonacci Numbers. >>> tribonacci(5) [0, 0, 1, 1, 2] >>> tribonacci(8) [0, 0, 1, 1, 2, 4, 7, 13] """ dp = [0] * num dp[2] = 1 for i in range(3, num): dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] return dp if __name__ == "__main__": import doctest doctest.testmod()
Viterbi Algorithm, to find the most likely path of states from the start and the expected output. https:en.wikipedia.orgwikiViterbialgorithm sdafads Wikipedia example observations normal, cold, dizzy states Healthy, Fever startp Healthy: 0.6, Fever: 0.4 transp ... Healthy: Healthy: 0.7, Fever: 0.3, ... Fever: Healthy: 0.4, Fever: 0.6, ... emitp ... Healthy: normal: 0.5, cold: 0.4, dizzy: 0.1, ... Fever: normal: 0.1, cold: 0.3, dizzy: 0.6, ... viterbiobservations, states, startp, transp, emitp 'Healthy', 'Healthy', 'Fever' viterbi, states, startp, transp, emitp Traceback most recent call last: ... ValueError: There's an empty parameter viterbiobservations, , startp, transp, emitp Traceback most recent call last: ... ValueError: There's an empty parameter viterbiobservations, states, , transp, emitp Traceback most recent call last: ... ValueError: There's an empty parameter viterbiobservations, states, startp, , emitp Traceback most recent call last: ... ValueError: There's an empty parameter viterbiobservations, states, startp, transp, Traceback most recent call last: ... ValueError: There's an empty parameter viterbiinvalid, states, startp, transp, emitp Traceback most recent call last: ... ValueError: observationsspace must be a list viterbivalid, 123, states, startp, transp, emitp Traceback most recent call last: ... ValueError: observationsspace must be a list of strings viterbiobservations, invalid, startp, transp, emitp Traceback most recent call last: ... ValueError: statesspace must be a list viterbiobservations, valid, 123, startp, transp, emitp Traceback most recent call last: ... ValueError: statesspace must be a list of strings viterbiobservations, states, invalid, transp, emitp Traceback most recent call last: ... ValueError: initialprobabilities must be a dict viterbiobservations, states, 2:2, transp, emitp Traceback most recent call last: ... ValueError: initialprobabilities all keys must be strings viterbiobservations, states, a:2, transp, emitp Traceback most recent call last: ... ValueError: initialprobabilities all values must be float viterbiobservations, states, startp, invalid, emitp Traceback most recent call last: ... ValueError: transitionprobabilities must be a dict viterbiobservations, states, startp, a:2, emitp Traceback most recent call last: ... ValueError: transitionprobabilities all values must be dict viterbiobservations, states, startp, 2:2:2, emitp Traceback most recent call last: ... ValueError: transitionprobabilities all keys must be strings viterbiobservations, states, startp, a:2:2, emitp Traceback most recent call last: ... ValueError: transitionprobabilities all keys must be strings viterbiobservations, states, startp, a:b:2, emitp Traceback most recent call last: ... ValueError: transitionprobabilities nested dictionary all values must be float viterbiobservations, states, startp, transp, invalid Traceback most recent call last: ... ValueError: emissionprobabilities must be a dict viterbiobservations, states, startp, transp, None Traceback most recent call last: ... ValueError: There's an empty parameter Creates data structures and fill initial step Fills the data structure with the probabilities of different transitions and pointers to previous states Calculates the argmax for probability function Update probabilities and pointers dicts The final observation argmax for given final observation Process pointers backwards observations normal, cold, dizzy states Healthy, Fever startp Healthy: 0.6, Fever: 0.4 transp ... Healthy: Healthy: 0.7, Fever: 0.3, ... Fever: Healthy: 0.4, Fever: 0.6, ... emitp ... Healthy: normal: 0.5, cold: 0.4, dizzy: 0.1, ... Fever: normal: 0.1, cold: 0.3, dizzy: 0.6, ... validationobservations, states, startp, transp, emitp validation, states, startp, transp, emitp Traceback most recent call last: ... ValueError: There's an empty parameter validatenotemptya, b, c:0.5, ... d: e: 0.6, f: g: 0.7 validatenotemptya, b, c:0.5, , f: g: 0.7 Traceback most recent call last: ... ValueError: There's an empty parameter validatenotemptya, b, None, d: e: 0.6, f: g: 0.7 Traceback most recent call last: ... ValueError: There's an empty parameter validatelistsa, b validatelists1234, b Traceback most recent call last: ... ValueError: observationsspace must be a list validatelistsa, 3 Traceback most recent call last: ... ValueError: statesspace must be a list of strings validatelista, mockname validatelista, mockname Traceback most recent call last: ... ValueError: mockname must be a list validatelist0.5, mockname Traceback most recent call last: ... ValueError: mockname must be a list of strings validatedictsc:0.5, d: e: 0.6, f: g: 0.7 validatedictsinvalid, d: e: 0.6, f: g: 0.7 Traceback most recent call last: ... ValueError: initialprobabilities must be a dict validatedictsc:0.5, 2: e: 0.6, f: g: 0.7 Traceback most recent call last: ... ValueError: transitionprobabilities all keys must be strings validatedictsc:0.5, d: e: 0.6, f: 2: 0.7 Traceback most recent call last: ... ValueError: emissionprobabilities all keys must be strings validatedictsc:0.5, d: e: 0.6, f: g: h Traceback most recent call last: ... ValueError: emissionprobabilities nested dictionary all values must be float validatenesteddicta:b: 0.5, mockname validatenesteddictinvalid, mockname Traceback most recent call last: ... ValueError: mockname must be a dict validatenesteddicta: 8, mockname Traceback most recent call last: ... ValueError: mockname all values must be dict validatenesteddicta:2: 0.5, mockname Traceback most recent call last: ... ValueError: mockname all keys must be strings validatenesteddicta:b: 4, mockname Traceback most recent call last: ... ValueError: mockname nested dictionary all values must be float validatedictb: 0.5, mockname, float validatedictinvalid, mockname, float Traceback most recent call last: ... ValueError: mockname must be a dict validatedicta: 8, mockname, dict Traceback most recent call last: ... ValueError: mockname all values must be dict validatedict2: 0.5, mockname,float, True Traceback most recent call last: ... ValueError: mockname all keys must be strings validatedictb: 4, mockname, float,True Traceback most recent call last: ... ValueError: mockname nested dictionary all values must be float
from typing import Any def viterbi( observations_space: list, states_space: list, initial_probabilities: dict, transition_probabilities: dict, emission_probabilities: dict, ) -> list: """ Viterbi Algorithm, to find the most likely path of states from the start and the expected output. https://en.wikipedia.org/wiki/Viterbi_algorithm sdafads Wikipedia example >>> observations = ["normal", "cold", "dizzy"] >>> states = ["Healthy", "Fever"] >>> start_p = {"Healthy": 0.6, "Fever": 0.4} >>> trans_p = { ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, ... } >>> emit_p = { ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, ... } >>> viterbi(observations, states, start_p, trans_p, emit_p) ['Healthy', 'Healthy', 'Fever'] >>> viterbi((), states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, (), start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, {}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, start_p, {}, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, start_p, trans_p, {}) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi("invalid", states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: observations_space must be a list >>> viterbi(["valid", 123], states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: observations_space must be a list of strings >>> viterbi(observations, "invalid", start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: states_space must be a list >>> viterbi(observations, ["valid", 123], start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: states_space must be a list of strings >>> viterbi(observations, states, "invalid", trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities must be a dict >>> viterbi(observations, states, {2:2}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities all keys must be strings >>> viterbi(observations, states, {"a":2}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities all values must be float >>> viterbi(observations, states, start_p, "invalid", emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities must be a dict >>> viterbi(observations, states, start_p, {"a":2}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all values must be dict >>> viterbi(observations, states, start_p, {2:{2:2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> viterbi(observations, states, start_p, {"a":{2:2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> viterbi(observations, states, start_p, {"a":{"b":2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities nested dictionary all values must be float >>> viterbi(observations, states, start_p, trans_p, "invalid") Traceback (most recent call last): ... ValueError: emission_probabilities must be a dict >>> viterbi(observations, states, start_p, trans_p, None) Traceback (most recent call last): ... ValueError: There's an empty parameter """ _validation( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) # Creates data structures and fill initial step probabilities: dict = {} pointers: dict = {} for state in states_space: observation = observations_space[0] probabilities[(state, observation)] = ( initial_probabilities[state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1, len(observations_space)): observation = observations_space[o] prior_observation = observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function arg_max = "" max_probability = -1 for k_state in states_space: probability = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: max_probability = probability arg_max = k_state # Update probabilities and pointers dicts probabilities[(state, observation)] = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = arg_max # The final observation final_observation = observations_space[len(observations_space) - 1] # argmax for given final observation arg_max = "" max_probability = -1 for k_state in states_space: probability = probabilities[(k_state, final_observation)] if probability > max_probability: max_probability = probability arg_max = k_state last_state = arg_max # Process pointers backwards previous = last_state result = [] for o in range(len(observations_space) - 1, -1, -1): result.append(previous) previous = pointers[previous, observations_space[o]] result.reverse() return result def _validation( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> observations = ["normal", "cold", "dizzy"] >>> states = ["Healthy", "Fever"] >>> start_p = {"Healthy": 0.6, "Fever": 0.4} >>> trans_p = { ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, ... } >>> emit_p = { ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, ... } >>> _validation(observations, states, start_p, trans_p, emit_p) >>> _validation([], states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter """ _validate_not_empty( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) _validate_lists(observations_space, states_space) _validate_dicts( initial_probabilities, transition_probabilities, emission_probabilities ) def _validate_not_empty( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, ... {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, {}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> _validate_not_empty(["a"], ["b"], None, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: There's an empty parameter """ if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("There's an empty parameter") def _validate_lists(observations_space: Any, states_space: Any) -> None: """ >>> _validate_lists(["a"], ["b"]) >>> _validate_lists(1234, ["b"]) Traceback (most recent call last): ... ValueError: observations_space must be a list >>> _validate_lists(["a"], [3]) Traceback (most recent call last): ... ValueError: states_space must be a list of strings """ _validate_list(observations_space, "observations_space") _validate_list(states_space, "states_space") def _validate_list(_object: Any, var_name: str) -> None: """ >>> _validate_list(["a"], "mock_name") >>> _validate_list("a", "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a list >>> _validate_list([0.5], "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a list of strings """ if not isinstance(_object, list): msg = f"{var_name} must be a list" raise ValueError(msg) else: for x in _object: if not isinstance(x, str): msg = f"{var_name} must be a list of strings" raise ValueError(msg) def _validate_dicts( initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) >>> _validate_dicts("invalid", {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: initial_probabilities must be a dict >>> _validate_dicts({"c":0.5}, {2: {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {2: 0.7}}) Traceback (most recent call last): ... ValueError: emission_probabilities all keys must be strings >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": "h"}}) Traceback (most recent call last): ... ValueError: emission_probabilities nested dictionary all values must be float """ _validate_dict(initial_probabilities, "initial_probabilities", float) _validate_nested_dict(transition_probabilities, "transition_probabilities") _validate_nested_dict(emission_probabilities, "emission_probabilities") def _validate_nested_dict(_object: Any, var_name: str) -> None: """ >>> _validate_nested_dict({"a":{"b": 0.5}}, "mock_name") >>> _validate_nested_dict("invalid", "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a dict >>> _validate_nested_dict({"a": 8}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name all values must be dict >>> _validate_nested_dict({"a":{2: 0.5}}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name all keys must be strings >>> _validate_nested_dict({"a":{"b": 4}}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name nested dictionary all values must be float """ _validate_dict(_object, var_name, dict) for x in _object.values(): _validate_dict(x, var_name, float, True) def _validate_dict( _object: Any, var_name: str, value_type: type, nested: bool = False ) -> None: """ >>> _validate_dict({"b": 0.5}, "mock_name", float) >>> _validate_dict("invalid", "mock_name", float) Traceback (most recent call last): ... ValueError: mock_name must be a dict >>> _validate_dict({"a": 8}, "mock_name", dict) Traceback (most recent call last): ... ValueError: mock_name all values must be dict >>> _validate_dict({2: 0.5}, "mock_name",float, True) Traceback (most recent call last): ... ValueError: mock_name all keys must be strings >>> _validate_dict({"b": 4}, "mock_name", float,True) Traceback (most recent call last): ... ValueError: mock_name nested dictionary all values must be float """ if not isinstance(_object, dict): msg = f"{var_name} must be a dict" raise ValueError(msg) if not all(isinstance(x, str) for x in _object): msg = f"{var_name} all keys must be strings" raise ValueError(msg) if not all(isinstance(x, value_type) for x in _object.values()): nested_text = "nested dictionary " if nested else "" msg = f"{var_name} {nested_text}all values must be {value_type.__name__}" raise ValueError(msg) if __name__ == "__main__": from doctest import testmod testmod()
Author : ilyas dahhou Date : Oct 7, 2023 Task: Given an input string and a pattern, implement wildcard pattern matching with support for '?' and '' where: '?' matches any single character. '' matches any sequence of characters including the empty sequence. The matching should cover the entire input string not partial. Runtime complexity: Om n The implementation was tested on the leetcode: https:leetcode.comproblemswildcardmatching ismatch, True ismatchaa, a False ismatchabc, abc True ismatchabc, c True ismatchabc, a True ismatchabc, a True ismatchabc, ?b? True ismatchabc, ? True ismatchabc, ad False ismatchabc, ac? False ismatch'baaabab','baba' False ismatch'baaabab','baab' True ismatch'aa','' True Fill in the first row Fill in the rest of the DP table
def is_match(string: str, pattern: str) -> bool: """ >>> is_match("", "") True >>> is_match("aa", "a") False >>> is_match("abc", "abc") True >>> is_match("abc", "*c") True >>> is_match("abc", "a*") True >>> is_match("abc", "*a*") True >>> is_match("abc", "?b?") True >>> is_match("abc", "*?") True >>> is_match("abc", "a*d") False >>> is_match("abc", "a*c?") False >>> is_match('baaabab','*****ba*****ba') False >>> is_match('baaabab','*****ba*****ab') True >>> is_match('aa','*') True """ dp = [[False] * (len(pattern) + 1) for _ in string + "1"] dp[0][0] = True # Fill in the first row for j, char in enumerate(pattern, 1): if char == "*": dp[0][j] = dp[0][j - 1] # Fill in the rest of the DP table for i, s_char in enumerate(string, 1): for j, p_char in enumerate(pattern, 1): if p_char in (s_char, "?"): dp[i][j] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": dp[i][j] = dp[i - 1][j] or dp[i][j - 1] return dp[len(string)][len(pattern)] if __name__ == "__main__": import doctest doctest.testmod() print(f"{is_match('baaabab','*****ba*****ab') = }")
Author : Alexander Pantyukhin Date : December 12, 2022 Task: Given a string and a list of words, return true if the string can be segmented into a spaceseparated sequence of one or more words. Note that the same word may be reused multiple times in the segmentation. Implementation notes: Trie Dynamic programming up down. The Trie will be used to store the words. It will be useful for scanning available words for the current position in the string. Leetcode: https:leetcode.comproblemswordbreakdescription Runtime: On n Space: On Return True if numbers have opposite signs False otherwise. wordbreakapplepenapple, apple,pen True wordbreakcatsandog, cats,dog,sand,and,cat False wordbreakcars, car,ca,rs True wordbreak'abc', False wordbreak123, 'a' Traceback most recent call last: ... ValueError: the string should be not empty string wordbreak'', 'a' Traceback most recent call last: ... ValueError: the string should be not empty string wordbreak'abc', 123 Traceback most recent call last: ... ValueError: the words should be a list of nonempty strings wordbreak'abc', '' Traceback most recent call last: ... ValueError: the words should be a list of nonempty strings Validation Build trie Dynamic programming method string 'a' isbreakable1 True
import functools from typing import Any def word_break(string: str, words: list[str]) -> bool: """ Return True if numbers have opposite signs False otherwise. >>> word_break("applepenapple", ["apple","pen"]) True >>> word_break("catsandog", ["cats","dog","sand","and","cat"]) False >>> word_break("cars", ["car","ca","rs"]) True >>> word_break('abc', []) False >>> word_break(123, ['a']) Traceback (most recent call last): ... ValueError: the string should be not empty string >>> word_break('', ['a']) Traceback (most recent call last): ... ValueError: the string should be not empty string >>> word_break('abc', [123]) Traceback (most recent call last): ... ValueError: the words should be a list of non-empty strings >>> word_break('abc', ['']) Traceback (most recent call last): ... ValueError: the words should be a list of non-empty strings """ # Validation if not isinstance(string, str) or len(string) == 0: raise ValueError("the string should be not empty string") if not isinstance(words, list) or not all( isinstance(item, str) and len(item) > 0 for item in words ): raise ValueError("the words should be a list of non-empty strings") # Build trie trie: dict[str, Any] = {} word_keeper_key = "WORD_KEEPER" for word in words: trie_node = trie for c in word: if c not in trie_node: trie_node[c] = {} trie_node = trie_node[c] trie_node[word_keeper_key] = True len_string = len(string) # Dynamic programming method @functools.cache def is_breakable(index: int) -> bool: """ >>> string = 'a' >>> is_breakable(1) True """ if index == len_string: return True trie_node = trie for i in range(index, len_string): trie_node = trie_node.get(string[i], None) if trie_node is None: return False if trie_node.get(word_keeper_key, False) and is_breakable(i + 1): return True return False return is_breakable(0) if __name__ == "__main__": import doctest doctest.testmod()
Calculate the apparent power in a singlephase AC circuit. Reference: https:en.wikipedia.orgwikiACpowerApparentpower apparentpower100, 5, 0, 0 5000j apparentpower100, 5, 90, 0 3.061616997868383e14500j apparentpower100, 5, 45, 60 129.40952255126027482.9629131445341j apparentpower200, 10, 30, 90 999.99999999999981732.0508075688776j Convert angles from degrees to radians Convert voltage and current to rectangular form Calculate apparent power
import cmath import math def apparent_power( voltage: float, current: float, voltage_angle: float, current_angle: float ) -> complex: """ Calculate the apparent power in a single-phase AC circuit. Reference: https://en.wikipedia.org/wiki/AC_power#Apparent_power >>> apparent_power(100, 5, 0, 0) (500+0j) >>> apparent_power(100, 5, 90, 0) (3.061616997868383e-14+500j) >>> apparent_power(100, 5, -45, -60) (-129.40952255126027-482.9629131445341j) >>> apparent_power(200, 10, -30, -90) (-999.9999999999998-1732.0508075688776j) """ # Convert angles from degrees to radians voltage_angle_rad = math.radians(voltage_angle) current_angle_rad = math.radians(current_angle) # Convert voltage and current to rectangular form voltage_rect = cmath.rect(voltage, voltage_angle_rad) current_rect = cmath.rect(current, current_angle_rad) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
This function can calculate the Builtin Voltage of a pn junction diode. This is calculated from the given three values. Examples builtinvoltagedonorconc1e17, acceptorconc1e17, intrinsicconc1e10 0.833370010652644 builtinvoltagedonorconc0, acceptorconc1600, intrinsicconc200 Traceback most recent call last: ... ValueError: Donor concentration should be positive builtinvoltagedonorconc1000, acceptorconc0, intrinsicconc1200 Traceback most recent call last: ... ValueError: Acceptor concentration should be positive builtinvoltagedonorconc1000, acceptorconc1000, intrinsicconc0 Traceback most recent call last: ... ValueError: Intrinsic concentration should be positive builtinvoltagedonorconc1000, acceptorconc3000, intrinsicconc2000 Traceback most recent call last: ... ValueError: Donor concentration should be greater than intrinsic concentration builtinvoltagedonorconc3000, acceptorconc1000, intrinsicconc2000 Traceback most recent call last: ... ValueError: Acceptor concentration should be greater than intrinsic concentration
from math import log from scipy.constants import Boltzmann, physical_constants T = 300 # TEMPERATURE (unit = K) def builtin_voltage( donor_conc: float, # donor concentration acceptor_conc: float, # acceptor concentration intrinsic_conc: float, # intrinsic concentration ) -> float: """ This function can calculate the Builtin Voltage of a pn junction diode. This is calculated from the given three values. Examples - >>> builtin_voltage(donor_conc=1e17, acceptor_conc=1e17, intrinsic_conc=1e10) 0.833370010652644 >>> builtin_voltage(donor_conc=0, acceptor_conc=1600, intrinsic_conc=200) Traceback (most recent call last): ... ValueError: Donor concentration should be positive >>> builtin_voltage(donor_conc=1000, acceptor_conc=0, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: Acceptor concentration should be positive >>> builtin_voltage(donor_conc=1000, acceptor_conc=1000, intrinsic_conc=0) Traceback (most recent call last): ... ValueError: Intrinsic concentration should be positive >>> builtin_voltage(donor_conc=1000, acceptor_conc=3000, intrinsic_conc=2000) Traceback (most recent call last): ... ValueError: Donor concentration should be greater than intrinsic concentration >>> builtin_voltage(donor_conc=3000, acceptor_conc=1000, intrinsic_conc=2000) Traceback (most recent call last): ... ValueError: Acceptor concentration should be greater than intrinsic concentration """ if donor_conc <= 0: raise ValueError("Donor concentration should be positive") elif acceptor_conc <= 0: raise ValueError("Acceptor concentration should be positive") elif intrinsic_conc <= 0: raise ValueError("Intrinsic concentration should be positive") elif donor_conc <= intrinsic_conc: raise ValueError( "Donor concentration should be greater than intrinsic concentration" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( "Acceptor concentration should be greater than intrinsic concentration" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
https:farside.ph.utexas.eduteaching316lecturesnode46.html Ceq C1 C2 ... Cn Calculate the equivalent resistance for any number of capacitors in parallel. capacitorparallel5.71389, 12, 3 20.71389 capacitorparallel5.71389, 12, 3 Traceback most recent call last: ... ValueError: Capacitor at index 2 has a negative value! Ceq 1 1C1 1C2 ... 1Cn capacitorseries5.71389, 12, 3 1.6901062252507735 capacitorseries5.71389, 12, 3 Traceback most recent call last: ... ValueError: Capacitor at index 2 has a negative or zero value! capacitorseries5.71389, 12, 0.000 Traceback most recent call last: ... ValueError: Capacitor at index 2 has a negative or zero value!
# https://farside.ph.utexas.edu/teaching/316/lectures/node46.html from __future__ import annotations def capacitor_parallel(capacitors: list[float]) -> float: """ Ceq = C1 + C2 + ... + Cn Calculate the equivalent resistance for any number of capacitors in parallel. >>> capacitor_parallel([5.71389, 12, 3]) 20.71389 >>> capacitor_parallel([5.71389, 12, -3]) Traceback (most recent call last): ... ValueError: Capacitor at index 2 has a negative value! """ sum_c = 0.0 for index, capacitor in enumerate(capacitors): if capacitor < 0: msg = f"Capacitor at index {index} has a negative value!" raise ValueError(msg) sum_c += capacitor return sum_c def capacitor_series(capacitors: list[float]) -> float: """ Ceq = 1/ (1/C1 + 1/C2 + ... + 1/Cn) >>> capacitor_series([5.71389, 12, 3]) 1.6901062252507735 >>> capacitor_series([5.71389, 12, -3]) Traceback (most recent call last): ... ValueError: Capacitor at index 2 has a negative or zero value! >>> capacitor_series([5.71389, 12, 0.000]) Traceback (most recent call last): ... ValueError: Capacitor at index 2 has a negative or zero value! """ first_sum = 0.0 for index, capacitor in enumerate(capacitors): if capacitor <= 0: msg = f"Capacitor at index {index} has a negative or zero value!" raise ValueError(msg) first_sum += 1 / capacitor return 1 / first_sum if __name__ == "__main__": import doctest doctest.testmod()
https:en.wikipedia.orgwikiChargecarrierdensity https:www.pveducation.orgpvcdrompnjunctionsequilibriumcarrierconcentration http:www.ece.utep.educoursesee3329ee3329StudyguideToCFundamentalsCarriersconcentrations.html This function can calculate any one of the three 1. Electron Concentration 2, Hole Concentration 3. Intrinsic Concentration given the other two. Examples carrierconcentrationelectronconc25, holeconc100, intrinsicconc0 'intrinsicconc', 50.0 carrierconcentrationelectronconc0, holeconc1600, intrinsicconc200 'electronconc', 25.0 carrierconcentrationelectronconc1000, holeconc0, intrinsicconc1200 'holeconc', 1440.0 carrierconcentrationelectronconc1000, holeconc400, intrinsicconc1200 Traceback most recent call last: ... ValueError: You cannot supply more or less than 2 values carrierconcentrationelectronconc1000, holeconc0, intrinsicconc1200 Traceback most recent call last: ... ValueError: Electron concentration cannot be negative in a semiconductor carrierconcentrationelectronconc0, holeconc400, intrinsicconc1200 Traceback most recent call last: ... ValueError: Hole concentration cannot be negative in a semiconductor carrierconcentrationelectronconc0, holeconc400, intrinsicconc1200 Traceback most recent call last: ... ValueError: Intrinsic concentration cannot be negative in a semiconductor
# https://en.wikipedia.org/wiki/Charge_carrier_density # https://www.pveducation.org/pvcdrom/pn-junctions/equilibrium-carrier-concentration # http://www.ece.utep.edu/courses/ee3329/ee3329/Studyguide/ToC/Fundamentals/Carriers/concentrations.html from __future__ import annotations def carrier_concentration( electron_conc: float, hole_conc: float, intrinsic_conc: float, ) -> tuple: """ This function can calculate any one of the three - 1. Electron Concentration 2, Hole Concentration 3. Intrinsic Concentration given the other two. Examples - >>> carrier_concentration(electron_conc=25, hole_conc=100, intrinsic_conc=0) ('intrinsic_conc', 50.0) >>> carrier_concentration(electron_conc=0, hole_conc=1600, intrinsic_conc=200) ('electron_conc', 25.0) >>> carrier_concentration(electron_conc=1000, hole_conc=0, intrinsic_conc=1200) ('hole_conc', 1440.0) >>> carrier_concentration(electron_conc=1000, hole_conc=400, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: You cannot supply more or less than 2 values >>> carrier_concentration(electron_conc=-1000, hole_conc=0, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: Electron concentration cannot be negative in a semiconductor >>> carrier_concentration(electron_conc=0, hole_conc=-400, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: Hole concentration cannot be negative in a semiconductor >>> carrier_concentration(electron_conc=0, hole_conc=400, intrinsic_conc=-1200) Traceback (most recent call last): ... ValueError: Intrinsic concentration cannot be negative in a semiconductor """ if (electron_conc, hole_conc, intrinsic_conc).count(0) != 1: raise ValueError("You cannot supply more or less than 2 values") elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative in a semiconductor") elif hole_conc < 0: raise ValueError("Hole concentration cannot be negative in a semiconductor") elif intrinsic_conc < 0: raise ValueError( "Intrinsic concentration cannot be negative in a semiconductor" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
source The ARRL Handbook for Radio Communications https:en.wikipedia.orgwikiRCtimeconstant Description When a capacitor is connected with a potential source AC or DC. It starts to charge at a general speed but when a resistor is connected in the circuit with in series to a capacitor then the capacitor charges slowly means it will take more time than usual. while the capacitor is being charged, the voltage is in exponential function with time. 'resistanceohms capacitancefarads' is called RCtimeconstant which may also be represented as tau. By using this RCtimeconstant we can find the voltage at any time 't' from the initiation of charging a capacitor with the help of the exponential function containing RC. Both at charging and discharging of a capacitor. Find capacitor voltage at any nth second after initiating its charging. Examples chargingcapacitorsourcevoltage.2,resistance.9,capacitance8.4,timesec.5 0.013 chargingcapacitorsourcevoltage2.2,resistance3.5,capacitance2.4,timesec9 1.446 chargingcapacitorsourcevoltage15,resistance200,capacitance20,timesec2 0.007 chargingcapacitor20, 2000, 30pow10,5, 4 19.975 chargingcapacitorsourcevoltage0,resistance10.0,capacitance.30,timesec3 Traceback most recent call last: ... ValueError: Source voltage must be positive. chargingcapacitorsourcevoltage20,resistance2000,capacitance30,timesec4 Traceback most recent call last: ... ValueError: Resistance must be positive. chargingcapacitorsourcevoltage30,resistance1500,capacitance0,timesec4 Traceback most recent call last: ... ValueError: Capacitance must be positive.
# source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RC_time_constant """ Description ----------- When a capacitor is connected with a potential source (AC or DC). It starts to charge at a general speed but when a resistor is connected in the circuit with in series to a capacitor then the capacitor charges slowly means it will take more time than usual. while the capacitor is being charged, the voltage is in exponential function with time. 'resistance(ohms) * capacitance(farads)' is called RC-timeconstant which may also be represented as τ (tau). By using this RC-timeconstant we can find the voltage at any time 't' from the initiation of charging a capacitor with the help of the exponential function containing RC. Both at charging and discharging of a capacitor. """ from math import exp # value of exp = 2.718281828459… def charging_capacitor( source_voltage: float, # voltage in volts. resistance: float, # resistance in ohms. capacitance: float, # capacitance in farads. time_sec: float, # time in seconds after charging initiation of capacitor. ) -> float: """ Find capacitor voltage at any nth second after initiating its charging. Examples -------- >>> charging_capacitor(source_voltage=.2,resistance=.9,capacitance=8.4,time_sec=.5) 0.013 >>> charging_capacitor(source_voltage=2.2,resistance=3.5,capacitance=2.4,time_sec=9) 1.446 >>> charging_capacitor(source_voltage=15,resistance=200,capacitance=20,time_sec=2) 0.007 >>> charging_capacitor(20, 2000, 30*pow(10,-5), 4) 19.975 >>> charging_capacitor(source_voltage=0,resistance=10.0,capacitance=.30,time_sec=3) Traceback (most recent call last): ... ValueError: Source voltage must be positive. >>> charging_capacitor(source_voltage=20,resistance=-2000,capacitance=30,time_sec=4) Traceback (most recent call last): ... ValueError: Resistance must be positive. >>> charging_capacitor(source_voltage=30,resistance=1500,capacitance=0,time_sec=4) Traceback (most recent call last): ... ValueError: Capacitance must be positive. """ if source_voltage <= 0: raise ValueError("Source voltage must be positive.") if resistance <= 0: raise ValueError("Resistance must be positive.") if capacitance <= 0: raise ValueError("Capacitance must be positive.") return round(source_voltage * (1 - exp(-time_sec / (resistance * capacitance))), 3) if __name__ == "__main__": import doctest doctest.testmod()
source The ARRL Handbook for Radio Communications https:en.wikipedia.orgwikiRLcircuit Description Inductor is a passive electronic device which stores energy but unlike capacitor, it stores energy in its 'magnetic field' or 'magnetostatic field'. When inductor is connected to 'DC' current source nothing happens it just works like a wire because it's real effect cannot be seen while 'DC' is connected, its not even going to store energy. Inductor stores energy only when it is working on 'AC' current. Connecting a inductor in series with a resistorwhen R 0 to a 'AC' potential source, from zero to a finite value causes a sudden voltage to induced in inductor which opposes the current. which results in initially slowly current rise. However it would cease if there is no further changes in current. With resistance zero current will never stop rising. 'Resistanceohms Inductancehenrys' is known as RLtimeconstant. It also represents as tau. While the charging of a inductor with a resistor results in a exponential function. when inductor is connected across 'AC' potential source. It starts to store the energy in its 'magnetic field'.with the help 'RLtimeconstant' we can find current at any time in inductor while it is charging. Find inductor current at any nth second after initiating its charging. Examples charginginductorsourcevoltage5.8,resistance1.5,inductance2.3,time2 2.817 charginginductorsourcevoltage8,resistance5,inductance3,time2 1.543 charginginductorsourcevoltage8,resistance5pow10,2,inductance3,time2 0.016 charginginductorsourcevoltage8,resistance100,inductance15,time12 Traceback most recent call last: ... ValueError: Source voltage must be positive. charginginductorsourcevoltage80,resistance15,inductance100,time5 Traceback most recent call last: ... ValueError: Resistance must be positive. charginginductorsourcevoltage12,resistance200,inductance20,time5 Traceback most recent call last: ... ValueError: Inductance must be positive. charginginductorsourcevoltage0,resistance200,inductance20,time5 Traceback most recent call last: ... ValueError: Source voltage must be positive. charginginductorsourcevoltage10,resistance0,inductance20,time5 Traceback most recent call last: ... ValueError: Resistance must be positive. charginginductorsourcevoltage15, resistance25, inductance0, time5 Traceback most recent call last: ... ValueError: Inductance must be positive.
# source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RL_circuit """ Description ----------- Inductor is a passive electronic device which stores energy but unlike capacitor, it stores energy in its 'magnetic field' or 'magnetostatic field'. When inductor is connected to 'DC' current source nothing happens it just works like a wire because it's real effect cannot be seen while 'DC' is connected, its not even going to store energy. Inductor stores energy only when it is working on 'AC' current. Connecting a inductor in series with a resistor(when R = 0) to a 'AC' potential source, from zero to a finite value causes a sudden voltage to induced in inductor which opposes the current. which results in initially slowly current rise. However it would cease if there is no further changes in current. With resistance zero current will never stop rising. 'Resistance(ohms) / Inductance(henrys)' is known as RL-timeconstant. It also represents as τ (tau). While the charging of a inductor with a resistor results in a exponential function. when inductor is connected across 'AC' potential source. It starts to store the energy in its 'magnetic field'.with the help 'RL-time-constant' we can find current at any time in inductor while it is charging. """ from math import exp # value of exp = 2.718281828459… def charging_inductor( source_voltage: float, # source_voltage should be in volts. resistance: float, # resistance should be in ohms. inductance: float, # inductance should be in henrys. time: float, # time should in seconds. ) -> float: """ Find inductor current at any nth second after initiating its charging. Examples -------- >>> charging_inductor(source_voltage=5.8,resistance=1.5,inductance=2.3,time=2) 2.817 >>> charging_inductor(source_voltage=8,resistance=5,inductance=3,time=2) 1.543 >>> charging_inductor(source_voltage=8,resistance=5*pow(10,2),inductance=3,time=2) 0.016 >>> charging_inductor(source_voltage=-8,resistance=100,inductance=15,time=12) Traceback (most recent call last): ... ValueError: Source voltage must be positive. >>> charging_inductor(source_voltage=80,resistance=-15,inductance=100,time=5) Traceback (most recent call last): ... ValueError: Resistance must be positive. >>> charging_inductor(source_voltage=12,resistance=200,inductance=-20,time=5) Traceback (most recent call last): ... ValueError: Inductance must be positive. >>> charging_inductor(source_voltage=0,resistance=200,inductance=20,time=5) Traceback (most recent call last): ... ValueError: Source voltage must be positive. >>> charging_inductor(source_voltage=10,resistance=0,inductance=20,time=5) Traceback (most recent call last): ... ValueError: Resistance must be positive. >>> charging_inductor(source_voltage=15, resistance=25, inductance=0, time=5) Traceback (most recent call last): ... ValueError: Inductance must be positive. """ if source_voltage <= 0: raise ValueError("Source voltage must be positive.") if resistance <= 0: raise ValueError("Resistance must be positive.") if inductance <= 0: raise ValueError("Inductance must be positive.") return round( source_voltage / resistance * (1 - exp((-time * resistance) / inductance)), 3 ) if __name__ == "__main__": import doctest doctest.testmod()
https:en.wikipedia.orgwikiCircularconvolution Circular convolution, also known as cyclic convolution, is a special case of periodic convolution, which is the convolution of two periodic functions that have the same period. Periodic convolution arises, for example, in the context of the discretetime Fourier transform DTFT. In particular, the DTFT of the product of two discrete sequences is the periodic convolution of the DTFTs of the individual sequences. And each DTFT is a periodic summation of a continuous Fourier transform function. Source: https:en.wikipedia.orgwikiCircularconvolution This class stores the first and second signal and performs the circular convolution First signal and second signal are stored as 1D array This function performs the circular convolution of the first and second signal using matrix method Usage: import circularconvolution as cc convolution cc.CircularConvolution convolution.circularconvolution 10, 10, 6, 14 convolution.firstsignal 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6 convolution.secondsignal 0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5 convolution.circularconvolution 5.2, 6.0, 6.48, 6.64, 6.48, 6.0, 5.2, 4.08 convolution.firstsignal 1, 1, 2, 2 convolution.secondsignal 0.5, 1, 1, 2, 0.75 convolution.circularconvolution 6.25, 3.0, 1.5, 2.0, 2.75 convolution.firstsignal 1, 1, 2, 3, 1 convolution.secondsignal 1, 2, 3 convolution.circularconvolution 8, 2, 3, 4, 11 create a zero matrix of maxlength x maxlength fills the smaller signal with zeros to make both signals of same length Fills the matrix in the following way assuming 'x' is the signal of length 4 x0, x3, x2, x1, x1, x0, x3, x2, x2, x1, x0, x3, x3, x2, x1, x0 multiply the matrix with the first signal roundingoff to two decimal places
# https://en.wikipedia.org/wiki/Circular_convolution """ Circular convolution, also known as cyclic convolution, is a special case of periodic convolution, which is the convolution of two periodic functions that have the same period. Periodic convolution arises, for example, in the context of the discrete-time Fourier transform (DTFT). In particular, the DTFT of the product of two discrete sequences is the periodic convolution of the DTFTs of the individual sequences. And each DTFT is a periodic summation of a continuous Fourier transform function. Source: https://en.wikipedia.org/wiki/Circular_convolution """ import doctest from collections import deque import numpy as np class CircularConvolution: """ This class stores the first and second signal and performs the circular convolution """ def __init__(self) -> None: """ First signal and second signal are stored as 1-D array """ self.first_signal = [2, 1, 2, -1] self.second_signal = [1, 2, 3, 4] def circular_convolution(self) -> list[float]: """ This function performs the circular convolution of the first and second signal using matrix method Usage: >>> import circular_convolution as cc >>> convolution = cc.CircularConvolution() >>> convolution.circular_convolution() [10, 10, 6, 14] >>> convolution.first_signal = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6] >>> convolution.second_signal = [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5] >>> convolution.circular_convolution() [5.2, 6.0, 6.48, 6.64, 6.48, 6.0, 5.2, 4.08] >>> convolution.first_signal = [-1, 1, 2, -2] >>> convolution.second_signal = [0.5, 1, -1, 2, 0.75] >>> convolution.circular_convolution() [6.25, -3.0, 1.5, -2.0, -2.75] >>> convolution.first_signal = [1, -1, 2, 3, -1] >>> convolution.second_signal = [1, 2, 3] >>> convolution.circular_convolution() [8, -2, 3, 4, 11] """ length_first_signal = len(self.first_signal) length_second_signal = len(self.second_signal) max_length = max(length_first_signal, length_second_signal) # create a zero matrix of max_length x max_length matrix = [[0] * max_length for i in range(max_length)] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) """ Fills the matrix in the following way assuming 'x' is the signal of length 4 [ [x[0], x[3], x[2], x[1]], [x[1], x[0], x[3], x[2]], [x[2], x[1], x[0], x[3]], [x[3], x[2], x[1], x[0]] ] """ for i in range(max_length): rotated_signal = deque(self.second_signal) rotated_signal.rotate(i) for j, item in enumerate(rotated_signal): matrix[i][j] += item # multiply the matrix with the first signal final_signal = np.matmul(np.transpose(matrix), np.transpose(self.first_signal)) # rounding-off to two decimal places return [round(i, 2) for i in final_signal] if __name__ == "__main__": doctest.testmod()
https:en.wikipedia.orgwikiCoulomb27slaw Apply Coulomb's Law on any three given values. These can be force, charge1, charge2, or distance, and then in a Python dict return namevalue pair of the zero value. Coulomb's Law states that the magnitude of the electrostatic force of attraction or repulsion between two point charges is directly proportional to the product of the magnitudes of charges and inversely proportional to the square of the distance between them. Reference Coulomb 1785 Premier mmoire sur llectricit et le magntisme, Histoire de lAcadmie Royale des Sciences, pp. 569577. Parameters force : float with units in Newtons charge1 : float with units in Coulombs charge2 : float with units in Coulombs distance : float with units in meters Returns result : dict namevalue pair of the zero value couloumbslawforce0, charge13, charge25, distance2000 'force': 33705.0 couloumbslawforce10, charge13, charge25, distance0 'distance': 116112.01488218177 couloumbslawforce10, charge10, charge25, distance2000 'charge1': 0.0008900756564307966 couloumbslawforce0, charge10, charge25, distance2000 Traceback most recent call last: ... ValueError: One and only one argument must be 0 couloumbslawforce0, charge13, charge25, distance2000 Traceback most recent call last: ... ValueError: Distance cannot be negative
# https://en.wikipedia.org/wiki/Coulomb%27s_law from __future__ import annotations COULOMBS_CONSTANT = 8.988e9 # units = N * m^s * C^-2 def couloumbs_law( force: float, charge1: float, charge2: float, distance: float ) -> dict[str, float]: """ Apply Coulomb's Law on any three given values. These can be force, charge1, charge2, or distance, and then in a Python dict return name/value pair of the zero value. Coulomb's Law states that the magnitude of the electrostatic force of attraction or repulsion between two point charges is directly proportional to the product of the magnitudes of charges and inversely proportional to the square of the distance between them. Reference ---------- Coulomb (1785) "Premier mémoire sur l’électricité et le magnétisme," Histoire de l’Académie Royale des Sciences, pp. 569–577. Parameters ---------- force : float with units in Newtons charge1 : float with units in Coulombs charge2 : float with units in Coulombs distance : float with units in meters Returns ------- result : dict name/value pair of the zero value >>> couloumbs_law(force=0, charge1=3, charge2=5, distance=2000) {'force': 33705.0} >>> couloumbs_law(force=10, charge1=3, charge2=5, distance=0) {'distance': 116112.01488218177} >>> couloumbs_law(force=10, charge1=0, charge2=5, distance=2000) {'charge1': 0.0008900756564307966} >>> couloumbs_law(force=0, charge1=0, charge2=5, distance=2000) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> couloumbs_law(force=0, charge1=3, charge2=5, distance=-2000) Traceback (most recent call last): ... ValueError: Distance cannot be negative """ charge_product = abs(charge1 * charge2) if (force, charge1, charge2, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if distance < 0: raise ValueError("Distance cannot be negative") if force == 0: force = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif charge1 == 0: charge1 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge2) return {"charge1": charge1} elif charge2 == 0: charge2 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge1) return {"charge2": charge2} elif distance == 0: distance = (COULOMBS_CONSTANT * charge_product / abs(force)) ** 0.5 return {"distance": distance} raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
This function can calculate any one of the three 1. Conductivity 2. Electron Concentration 3. Electron Mobility This is calculated from the other two provided values Examples electricconductivityconductivity25, electronconc100, mobility0 'mobility', 1.5604519068722301e18 electricconductivityconductivity0, electronconc1600, mobility200 'conductivity', 5.12672e14 electricconductivityconductivity1000, electronconc0, mobility1200 'electronconc', 5.201506356240767e18
from __future__ import annotations ELECTRON_CHARGE = 1.6021e-19 # units = C def electric_conductivity( conductivity: float, electron_conc: float, mobility: float, ) -> tuple[str, float]: """ This function can calculate any one of the three - 1. Conductivity 2. Electron Concentration 3. Electron Mobility This is calculated from the other two provided values Examples - >>> electric_conductivity(conductivity=25, electron_conc=100, mobility=0) ('mobility', 1.5604519068722301e+18) >>> electric_conductivity(conductivity=0, electron_conc=1600, mobility=200) ('conductivity', 5.12672e-14) >>> electric_conductivity(conductivity=1000, electron_conc=0, mobility=1200) ('electron_conc', 5.201506356240767e+18) """ if (conductivity, electron_conc, mobility).count(0) != 1: raise ValueError("You cannot supply more or less than 2 values") elif conductivity < 0: raise ValueError("Conductivity cannot be negative") elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative") elif mobility < 0: raise ValueError("mobility cannot be negative") elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
https:en.m.wikipedia.orgwikiElectricpower This function can calculate any one of the three voltage, current, power, fundamental value of electrical system. examples are below: electricpowervoltage0, current2, power5 Resultname'voltage', value2.5 electricpowervoltage2, current2, power0 Resultname'power', value4.0 electricpowervoltage2, current3, power0 Resultname'power', value6.0 electricpowervoltage2, current4, power2 Traceback most recent call last: ... ValueError: Only one argument must be 0 electricpowervoltage0, current0, power2 Traceback most recent call last: ... ValueError: Only one argument must be 0 electricpowervoltage0, current2, power4 Traceback most recent call last: ... ValueError: Power cannot be negative in any electricalelectronics system electricpowervoltage2.2, current2.2, power0 Resultname'power', value4.84
# https://en.m.wikipedia.org/wiki/Electric_power from __future__ import annotations from typing import NamedTuple class Result(NamedTuple): name: str value: float def electric_power(voltage: float, current: float, power: float) -> tuple: """ This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below: >>> electric_power(voltage=0, current=2, power=5) Result(name='voltage', value=2.5) >>> electric_power(voltage=2, current=2, power=0) Result(name='power', value=4.0) >>> electric_power(voltage=-2, current=3, power=0) Result(name='power', value=6.0) >>> electric_power(voltage=2, current=4, power=2) Traceback (most recent call last): ... ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=0, power=2) Traceback (most recent call last): ... ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=2, power=-4) Traceback (most recent call last): ... ValueError: Power cannot be negative in any electrical/electronics system >>> electric_power(voltage=2.2, current=2.2, power=0) Result(name='power', value=4.84) """ if (voltage, current, power).count(0) != 1: raise ValueError("Only one argument must be 0") elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return Result("voltage", power / current) elif current == 0: return Result("current", power / voltage) elif power == 0: return Result("power", float(round(abs(voltage * current), 2))) else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
Electrical impedance is the measure of the opposition that a circuit presents to a current when a voltage is applied. Impedance extends the concept of resistance to alternating current AC circuits. Source: https:en.wikipedia.orgwikiElectricalimpedance Apply Electrical Impedance formula, on any two given electrical values, which can be resistance, reactance, and impedance, and then in a Python dict return namevalue pair of the zero value. electricalimpedance3,4,0 'impedance': 5.0 electricalimpedance0,4,5 'resistance': 3.0 electricalimpedance3,0,5 'reactance': 4.0 electricalimpedance3,4,5 Traceback most recent call last: ... ValueError: One and only one argument must be 0
from __future__ import annotations from math import pow, sqrt def electrical_impedance( resistance: float, reactance: float, impedance: float ) -> dict[str, float]: """ Apply Electrical Impedance formula, on any two given electrical values, which can be resistance, reactance, and impedance, and then in a Python dict return name/value pair of the zero value. >>> electrical_impedance(3,4,0) {'impedance': 5.0} >>> electrical_impedance(0,4,5) {'resistance': 3.0} >>> electrical_impedance(3,0,5) {'reactance': 4.0} >>> electrical_impedance(3,4,5) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 """ if (resistance, reactance, impedance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance == 0: return {"resistance": sqrt(pow(impedance, 2) - pow(reactance, 2))} elif reactance == 0: return {"reactance": sqrt(pow(impedance, 2) - pow(resistance, 2))} elif impedance == 0: return {"impedance": sqrt(pow(resistance, 2) + pow(reactance, 2))} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
Calculate the frequency andor duty cycle of an astable 555 timer. https:en.wikipedia.orgwiki555timerICAstable These functions take in the value of the external resistances in ohms and capacitance in Microfarad, and calculates the following: Freq 1.44 R1 2 x R2 x C1 ... in Hz where Freq is the frequency, R1 is the first resistance in ohms, R2 is the second resistance in ohms, C1 is the capacitance in Microfarads. Duty Cycle R1 R2 R1 2 x R2 x 100 ... in where R1 is the first resistance in ohms, R2 is the second resistance in ohms. Usage examples: astablefrequencyresistance145, resistance245, capacitance7 1523.8095238095239 astablefrequencyresistance1356, resistance2234, capacitance976 1.7905459175553078 astablefrequencyresistance12, resistance21, capacitance2 Traceback most recent call last: ... ValueError: All values must be positive astablefrequencyresistance145, resistance245, capacitance0 Traceback most recent call last: ... ValueError: All values must be positive Usage examples: astabledutycycleresistance145, resistance245 66.66666666666666 astabledutycycleresistance1356, resistance2234 71.60194174757282 astabledutycycleresistance12, resistance21 Traceback most recent call last: ... ValueError: All values must be positive astabledutycycleresistance10, resistance20 Traceback most recent call last: ... ValueError: All values must be positive
from __future__ import annotations """ Calculate the frequency and/or duty cycle of an astable 555 timer. * https://en.wikipedia.org/wiki/555_timer_IC#Astable These functions take in the value of the external resistances (in ohms) and capacitance (in Microfarad), and calculates the following: ------------------------------------- | Freq = 1.44 /[( R1+ 2 x R2) x C1] | ... in Hz ------------------------------------- where Freq is the frequency, R1 is the first resistance in ohms, R2 is the second resistance in ohms, C1 is the capacitance in Microfarads. ------------------------------------------------ | Duty Cycle = (R1 + R2) / (R1 + 2 x R2) x 100 | ... in % ------------------------------------------------ where R1 is the first resistance in ohms, R2 is the second resistance in ohms. """ def astable_frequency( resistance_1: float, resistance_2: float, capacitance: float ) -> float: """ Usage examples: >>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=7) 1523.8095238095239 >>> astable_frequency(resistance_1=356, resistance_2=234, capacitance=976) 1.7905459175553078 >>> astable_frequency(resistance_1=2, resistance_2=-1, capacitance=2) Traceback (most recent call last): ... ValueError: All values must be positive >>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=0) Traceback (most recent call last): ... ValueError: All values must be positive """ if resistance_1 <= 0 or resistance_2 <= 0 or capacitance <= 0: raise ValueError("All values must be positive") return (1.44 / ((resistance_1 + 2 * resistance_2) * capacitance)) * 10**6 def astable_duty_cycle(resistance_1: float, resistance_2: float) -> float: """ Usage examples: >>> astable_duty_cycle(resistance_1=45, resistance_2=45) 66.66666666666666 >>> astable_duty_cycle(resistance_1=356, resistance_2=234) 71.60194174757282 >>> astable_duty_cycle(resistance_1=2, resistance_2=-1) Traceback (most recent call last): ... ValueError: All values must be positive >>> astable_duty_cycle(resistance_1=0, resistance_2=0) Traceback (most recent call last): ... ValueError: All values must be positive """ if resistance_1 <= 0 or resistance_2 <= 0: raise ValueError("All values must be positive") return (resistance_1 + resistance_2) / (resistance_1 + 2 * resistance_2) * 100 if __name__ == "__main__": import doctest doctest.testmod()