Description
stringlengths
18
161k
Code
stringlengths
15
300k
question given a binary matrix mat of size n m find out the maximum size square submatrix with all 1s example 1 input n 2 m 2 mat 1 1 1 1 output 2 explanation the maximum size of the square submatrix is 2 the matrix itself is the maximum sized submatrix in this case example 2 input n 2 m 2 mat 0 0 0 0 output 0 explanation there is no 1 in the matrix approach we initialize another matrix dp with the same dimensions as the original one initialized with all 0s dparrayi j represents the side length of the maximum square whose bottom right corner is the cell with index i j in the original matrix starting from index 0 0 for every 1 found in the original matrix we update the value of the current element as dparrayi jdparraydpi1 j dparrayi1 j1 dparrayi j1 1 function updates the largestsquarearea0 if recursive call found square with maximum area we aren t using dparray here so the time complexity would be exponential largestsquareareainmatrixtopdownapproch2 2 1 1 1 1 2 largestsquareareainmatrixtopdownapproch2 2 0 0 0 0 0 base case function updates the largestsquarearea0 if recursive call found square with maximum area we are using dparray here so the time complexity would be on2 largestsquareareainmatrixtopdownapprochwithdp2 2 1 1 1 1 2 largestsquareareainmatrixtopdownapprochwithdp2 2 0 0 0 0 0 function updates the largestsquarearea using bottom up approach largestsquareareainmatrixbottomup2 2 1 1 1 1 2 largestsquareareainmatrixbottomup2 2 0 0 0 0 0 function updates the largestsquarearea using bottom up approach with space optimization largestsquareareainmatrixbottomupspaceoptimization2 2 1 1 1 1 2 largestsquareareainmatrixbottomupspaceoptimization2 2 0 0 0 0 0 function updates the largest_square_area 0 if recursive call found square with maximum area we aren t using dp_array here so the time complexity would be exponential largest_square_area_in_matrix_top_down_approch 2 2 1 1 1 1 2 largest_square_area_in_matrix_top_down_approch 2 2 0 0 0 0 0 base case function updates the largest_square_area 0 if recursive call found square with maximum area we are using dp_array here so the time complexity would be o n 2 largest_square_area_in_matrix_top_down_approch_with_dp 2 2 1 1 1 1 2 largest_square_area_in_matrix_top_down_approch_with_dp 2 2 0 0 0 0 0 function updates the largest_square_area using bottom up approach largest_square_area_in_matrix_bottom_up 2 2 1 1 1 1 2 largest_square_area_in_matrix_bottom_up 2 2 0 0 0 0 0 function updates the largest_square_area using bottom up approach with space optimization largest_square_area_in_matrix_bottom_up_space_optimization 2 2 1 1 1 1 2 largest_square_area_in_matrix_bottom_up_space_optimization 2 2 0 0 0 0 0
def largest_square_area_in_matrix_top_down_approch( rows: int, cols: int, mat: list[list[int]] ) -> int: def update_area_of_max_square(row: int, col: int) -> int: if row >= rows or col >= cols: return 0 right = update_area_of_max_square(row, col + 1) diagonal = update_area_of_max_square(row + 1, col + 1) down = update_area_of_max_square(row + 1, col) if mat[row][col]: sub_problem_sol = 1 + min([right, diagonal, down]) largest_square_area[0] = max(largest_square_area[0], sub_problem_sol) return sub_problem_sol else: return 0 largest_square_area = [0] update_area_of_max_square(0, 0) return largest_square_area[0] def largest_square_area_in_matrix_top_down_approch_with_dp( rows: int, cols: int, mat: list[list[int]] ) -> int: def update_area_of_max_square_using_dp_array( row: int, col: int, dp_array: list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] right = update_area_of_max_square_using_dp_array(row, col + 1, dp_array) diagonal = update_area_of_max_square_using_dp_array(row + 1, col + 1, dp_array) down = update_area_of_max_square_using_dp_array(row + 1, col, dp_array) if mat[row][col]: sub_problem_sol = 1 + min([right, diagonal, down]) largest_square_area[0] = max(largest_square_area[0], sub_problem_sol) dp_array[row][col] = sub_problem_sol return sub_problem_sol else: return 0 largest_square_area = [0] dp_array = [[-1] * cols for _ in range(rows)] update_area_of_max_square_using_dp_array(0, 0, dp_array) return largest_square_area[0] def largest_square_area_in_matrix_bottom_up( rows: int, cols: int, mat: list[list[int]] ) -> int: dp_array = [[0] * (cols + 1) for _ in range(rows + 1)] largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): right = dp_array[row][col + 1] diagonal = dp_array[row + 1][col + 1] bottom = dp_array[row + 1][col] if mat[row][col] == 1: dp_array[row][col] = 1 + min(right, diagonal, bottom) largest_square_area = max(dp_array[row][col], largest_square_area) else: dp_array[row][col] = 0 return largest_square_area def largest_square_area_in_matrix_bottom_up_space_optimization( rows: int, cols: int, mat: list[list[int]] ) -> int: current_row = [0] * (cols + 1) next_row = [0] * (cols + 1) largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): right = current_row[col + 1] diagonal = next_row[col + 1] bottom = next_row[col] if mat[row][col] == 1: current_row[col] = 1 + min(right, diagonal, bottom) largest_square_area = max(current_row[col], largest_square_area) else: current_row[col] = 0 next_row = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
an oop approach to representing and manipulating matrices matrix object generated from a 2d array where each element is an array representing a row rows can contain type int or float common operations and information available rows 1 2 3 4 5 6 7 8 9 matrix matrixrows printmatrix 1 2 3 4 5 6 7 8 9 matrix rows and columns are available as 2d arrays matrix rows 1 2 3 4 5 6 7 8 9 matrix columns 1 4 7 2 5 8 3 6 9 order is returned as a tuple matrix order 3 3 squareness and invertability are represented as bool matrix issquare true matrix isinvertable false identity minors cofactors and adjugate are returned as matrices inverse can be a matrix or nonetype printmatrix identity 1 0 0 0 1 0 0 0 1 printmatrix minors 3 6 3 6 12 6 3 6 3 printmatrix cofactors 3 6 3 6 12 6 3 6 3 won t be apparent due to the nature of the cofactor matrix printmatrix adjugate 3 6 3 6 12 6 3 6 3 matrix inverse traceback most recent call last typeerror only matrices with a nonzero determinant have an inverse determinant is an int float or nonetype matrix determinant 0 negation scalar multiplication addition subtraction multiplication and exponentiation are available and all return a matrix printmatrix 1 2 3 4 5 6 7 8 9 matrix2 matrix 3 printmatrix2 3 6 9 12 15 18 21 24 27 printmatrix matrix2 4 8 12 16 20 24 28 32 36 printmatrix matrix2 2 4 6 8 10 12 14 16 18 printmatrix 3 468 576 684 1062 1305 1548 1656 2034 2412 matrices can also be modified matrix addrow10 11 12 printmatrix 1 2 3 4 5 6 7 8 9 10 11 12 matrix2 addcolumn8 16 32 printmatrix2 3 6 9 8 12 15 18 16 21 24 27 32 printmatrix matrix2 90 108 126 136 198 243 288 304 306 378 450 472 414 513 612 640 matrix information matrix manipulation matrix operations an oop approach to representing and manipulating matrices matrix object generated from a 2d array where each element is an array representing a row rows can contain type int or float common operations and information available rows 1 2 3 4 5 6 7 8 9 matrix matrix rows print matrix 1 2 3 4 5 6 7 8 9 matrix rows and columns are available as 2d arrays matrix rows 1 2 3 4 5 6 7 8 9 matrix columns 1 4 7 2 5 8 3 6 9 order is returned as a tuple matrix order 3 3 squareness and invertability are represented as bool matrix is_square true matrix is_invertable false identity minors cofactors and adjugate are returned as matrices inverse can be a matrix or nonetype print matrix identity 1 0 0 0 1 0 0 0 1 print matrix minors 3 6 3 6 12 6 3 6 3 print matrix cofactors 3 6 3 6 12 6 3 6 3 won t be apparent due to the nature of the cofactor matrix print matrix adjugate 3 6 3 6 12 6 3 6 3 matrix inverse traceback most recent call last typeerror only matrices with a non zero determinant have an inverse determinant is an int float or nonetype matrix determinant 0 negation scalar multiplication addition subtraction multiplication and exponentiation are available and all return a matrix print matrix 1 2 3 4 5 6 7 8 9 matrix2 matrix 3 print matrix2 3 6 9 12 15 18 21 24 27 print matrix matrix2 4 8 12 16 20 24 28 32 36 print matrix matrix2 2 4 6 8 10 12 14 16 18 print matrix 3 468 576 684 1062 1305 1548 1656 2034 2412 matrices can also be modified matrix add_row 10 11 12 print matrix 1 2 3 4 5 6 7 8 9 10 11 12 matrix2 add_column 8 16 32 print matrix2 3 6 9 8 12 15 18 16 21 24 27 32 print matrix matrix2 90 108 126 136 198 243 288 304 306 378 450 472 414 513 612 640 matrix information matrix manipulation matrix operations
from __future__ import annotations class Matrix: def __init__(self, rows: list[list[int]]): error = TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same number of values, each of which must be of type " "int or float." ) if len(rows) != 0: cols = len(rows[0]) if cols == 0: raise error for row in rows: if len(row) != cols: raise error for value in row: if not isinstance(value, (int, float)): raise error self.rows = rows else: self.rows = [] def columns(self) -> list[list[int]]: return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))] @property def num_rows(self) -> int: return len(self.rows) @property def num_columns(self) -> int: return len(self.rows[0]) @property def order(self) -> tuple[int, int]: return self.num_rows, self.num_columns @property def is_square(self) -> bool: return self.order[0] == self.order[1] def identity(self) -> Matrix: values = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows)] for row_num in range(self.num_rows) ] return Matrix(values) def determinant(self) -> int: if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0]) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns) ) def is_invertable(self) -> bool: return bool(self.determinant()) def get_minor(self, row: int, column: int) -> int: values = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns) if other_column != column ] for other_row in range(self.num_rows) if other_row != row ] return Matrix(values).determinant() def get_cofactor(self, row: int, column: int) -> int: if (row + column) % 2 == 0: return self.get_minor(row, column) return -1 * self.get_minor(row, column) def minors(self) -> Matrix: return Matrix( [ [self.get_minor(row, column) for column in range(self.num_columns)] for row in range(self.num_rows) ] ) def cofactors(self) -> Matrix: return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns) ] for row in range(self.minors().num_rows) ] ) def adjugate(self) -> Matrix: values = [ [self.cofactors().rows[column][row] for column in range(self.num_columns)] for row in range(self.num_rows) ] return Matrix(values) def inverse(self) -> Matrix: determinant = self.determinant() if not determinant: raise TypeError("Only matrices with a non-zero determinant have an inverse") return self.adjugate() * (1 / determinant) def __repr__(self) -> str: return str(self.rows) def __str__(self) -> str: if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0])) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(value) for value in row]) + ".]" for row in self.rows ] ) + "]" ) def add_row(self, row: list[int], position: int | None = None) -> None: type_error = TypeError("Row must be a list containing all ints and/or floats") if not isinstance(row, list): raise type_error for value in row: if not isinstance(value, (int, float)): raise type_error if len(row) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(row) else: self.rows = self.rows[0:position] + [row] + self.rows[position:] def add_column(self, column: list[int], position: int | None = None) -> None: type_error = TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(column, list): raise type_error for value in column: if not isinstance(value, (int, float)): raise type_error if len(column) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: self.rows = [self.rows[i] + [column[i]] for i in range(self.num_rows)] else: self.rows = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows) ] def __eq__(self, other: object) -> bool: if not isinstance(other, Matrix): return NotImplemented return self.rows == other.rows def __ne__(self, other: object) -> bool: return not self == other def __neg__(self) -> Matrix: return self * -1 def __add__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Addition requires matrices of the same order") return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __sub__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order") return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __mul__(self, other: Matrix | float) -> Matrix: if isinstance(other, (int, float)): return Matrix( [[int(element * other) for element in row] for row in self.rows] ) elif isinstance(other, Matrix): if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must " "be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(row, column) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) def __pow__(self, other: int) -> Matrix: if not isinstance(other, int): raise TypeError("A Matrix can only be raised to the power of an int") if not self.is_square: raise ValueError("Only square matrices can be raised to a power") if other == 0: return self.identity() if other < 0: if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) result = self for _ in range(other - 1): result *= self return result @classmethod def dot_product(cls, row: list[int], column: list[int]) -> int: return sum(row[i] * column[i] for i in range(len(row))) if __name__ == "__main__": import doctest doctest.testmod()
ojaswani file matrixmultiplicationrecursion py date 10062023 perform matrix multiplication using a recursive algorithm https en wikipedia orgwikimatrixmultiplication type matrix listlistint psfblack currenttly fails on this line issquare true issquarematrix1to4 true issquarematrix5to9high false matrixmultiplymatrix1to4 matrix5to8 19 22 43 50 param matrixa a square matrix param matrixb another square matrix with the same dimensions as matrixa return result of matrixa matrixb raises valueerror if the matrices cannot be multiplied matrixmultiplyrecursive matrixmultiplyrecursivematrix1to4 matrix5to8 19 22 43 50 matrixmultiplyrecursivematrixcountup matrixunordered 37 61 74 61 105 165 166 129 173 269 258 197 241 373 350 265 matrixmultiplyrecursivematrix1to4 matrix5to9wide traceback most recent call last valueerror invalid matrix dimensions matrixmultiplyrecursivematrix1to4 matrix5to9high traceback most recent call last valueerror invalid matrix dimensions matrixmultiplyrecursivematrix1to4 matrixcountup traceback most recent call last valueerror invalid matrix dimensions initialize the result matrix with zeros recursive multiplication of matrices param matrixa a square matrix param matrixb another square matrix with the same dimensions as matrixa param result result matrix param i index used for iteration during multiplication param j index used for iteration during multiplication param k index used for iteration during multiplication 0 1 doctests in inner functions are never run true perform the recursive matrix multiplication ojas wani file matrix_multiplication_recursion py date 10 06 2023 perform matrix multiplication using a recursive algorithm https en wikipedia org wiki matrix_multiplication type matrix list list int psf black currenttly fails on this line is_square true is_square matrix_1_to_4 true is_square matrix_5_to_9_high false matrix_multiply matrix_1_to_4 matrix_5_to_8 19 22 43 50 param matrix_a a square matrix param matrix_b another square matrix with the same dimensions as matrix_a return result of matrix_a matrix_b raises valueerror if the matrices cannot be multiplied matrix_multiply_recursive matrix_multiply_recursive matrix_1_to_4 matrix_5_to_8 19 22 43 50 matrix_multiply_recursive matrix_count_up matrix_unordered 37 61 74 61 105 165 166 129 173 269 258 197 241 373 350 265 matrix_multiply_recursive matrix_1_to_4 matrix_5_to_9_wide traceback most recent call last valueerror invalid matrix dimensions matrix_multiply_recursive matrix_1_to_4 matrix_5_to_9_high traceback most recent call last valueerror invalid matrix dimensions matrix_multiply_recursive matrix_1_to_4 matrix_count_up traceback most recent call last valueerror invalid matrix dimensions initialize the result matrix with zeros recursive multiplication of matrices param matrix_a a square matrix param matrix_b another square matrix with the same dimensions as matrix_a param result result matrix param i index used for iteration during multiplication param j index used for iteration during multiplication param k index used for iteration during multiplication 0 1 doctests in inner functions are never run true perform the recursive matrix multiplication
Matrix = list[list[int]] matrix_1_to_4 = [ [1, 2], [3, 4], ] matrix_5_to_8 = [ [5, 6], [7, 8], ] matrix_5_to_9_high = [ [5, 6], [7, 8], [9], ] matrix_5_to_9_wide = [ [5, 6], [7, 8, 9], ] matrix_count_up = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ] matrix_unordered = [ [5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1], [2, 6, 10, 14], ] matrices = ( matrix_1_to_4, matrix_5_to_8, matrix_5_to_9_high, matrix_5_to_9_wide, matrix_count_up, matrix_unordered, ) def is_square(matrix: Matrix) -> bool: len_matrix = len(matrix) return all(len(row) == len_matrix for row in matrix) def matrix_multiply(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: return [ [sum(a * b for a, b in zip(row, col)) for col in zip(*matrix_b)] for row in matrix_a ] def matrix_multiply_recursive(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: if not matrix_a or not matrix_b: return [] if not all( (len(matrix_a) == len(matrix_b), is_square(matrix_a), is_square(matrix_b)) ): raise ValueError("Invalid matrix dimensions") result = [[0] * len(matrix_b[0]) for _ in range(len(matrix_a))] def multiply( i_loop: int, j_loop: int, k_loop: int, matrix_a: Matrix, matrix_b: Matrix, result: Matrix, ) -> None: if i_loop >= len(matrix_a): return if j_loop >= len(matrix_b[0]): return multiply(i_loop + 1, 0, 0, matrix_a, matrix_b, result) if k_loop >= len(matrix_b): return multiply(i_loop, j_loop + 1, 0, matrix_a, matrix_b, result) result[i_loop][j_loop] += matrix_a[i_loop][k_loop] * matrix_b[k_loop][j_loop] return multiply(i_loop, j_loop, k_loop + 1, matrix_a, matrix_b, result) multiply(0, 0, 0, matrix_a, matrix_b, result) return result if __name__ == "__main__": from doctest import testmod failure_count, test_count = testmod() if not failure_count: matrix_a = matrices[0] for matrix_b in matrices[1:]: print("Multiplying:") for row in matrix_a: print(row) print("By:") for row in matrix_b: print(row) print("Result:") try: result = matrix_multiply_recursive(matrix_a, matrix_b) for row in result: print(row) assert result == matrix_multiply(matrix_a, matrix_b) except ValueError as e: print(f"{e!r}") print() matrix_a = matrix_b print("Benchmark:") from functools import partial from timeit import timeit mytimeit = partial(timeit, globals=globals(), number=100_000) for func in ("matrix_multiply", "matrix_multiply_recursive"): print(f"{func:>25}(): {mytimeit(f'{func}(matrix_count_up, matrix_unordered)')}")
functions for 2d matrix operations add1 2 3 4 2 3 4 5 3 5 7 9 add1 2 2 4 3 4 2 3 4 5 3 2 5 4 7 9 add1 2 4 5 3 7 3 4 3 5 5 7 7 14 12 16 add3 4 5 traceback most recent call last typeerror expected a matrix got intlist instead subtract1 2 3 4 2 3 4 5 1 1 1 1 subtract1 2 5 3 4 2 3 4 5 5 1 0 5 1 1 5 subtract3 4 5 traceback most recent call last typeerror expected a matrix got intlist instead scalarmultiply1 2 3 4 5 5 10 15 20 scalarmultiply1 4 2 3 3 4 5 7 0 11 5 15 20 multiply1 2 3 4 5 5 7 5 19 15 43 35 multiply1 2 5 3 4 5 5 5 7 5 22 5 17 5 46 5 37 5 multiply1 2 3 2 3 4 20 param n dimension for nxn matrix type n int return identity matrix of shape n n identity3 1 0 0 0 1 0 0 0 1 transpose1 2 3 4 doctest ellipsis map object at transpose1 2 3 4 returnmapfalse 1 3 2 4 transpose1 2 3 traceback most recent call last typeerror expected a matrix got intlist instead minor1 2 3 4 1 1 1 determinant1 2 3 4 2 determinant1 5 2 5 3 4 1 5 inverse1 2 3 4 2 0 1 0 1 5 0 5 inverse1 1 1 1 https stackoverflow comquestions20047519pythondocteststestfornone add 1 2 3 4 2 3 4 5 3 5 7 9 add 1 2 2 4 3 4 2 3 4 5 3 2 5 4 7 9 add 1 2 4 5 3 7 3 4 3 5 5 7 7 14 12 16 add 3 4 5 traceback most recent call last typeerror expected a matrix got int list instead subtract 1 2 3 4 2 3 4 5 1 1 1 1 subtract 1 2 5 3 4 2 3 4 5 5 1 0 5 1 1 5 subtract 3 4 5 traceback most recent call last typeerror expected a matrix got int list instead scalar_multiply 1 2 3 4 5 5 10 15 20 scalar_multiply 1 4 2 3 3 4 5 7 0 11 5 15 20 multiply 1 2 3 4 5 5 7 5 19 15 43 35 multiply 1 2 5 3 4 5 5 5 7 5 22 5 17 5 46 5 37 5 multiply 1 2 3 2 3 4 20 param n dimension for nxn matrix type n int return identity matrix of shape n n identity 3 1 0 0 0 1 0 0 0 1 transpose 1 2 3 4 doctest ellipsis map object at transpose 1 2 3 4 return_map false 1 3 2 4 transpose 1 2 3 traceback most recent call last typeerror expected a matrix got int list instead minor 1 2 3 4 1 1 1 determinant 1 2 3 4 2 determinant 1 5 2 5 3 4 1 5 inverse 1 2 3 4 2 0 1 0 1 5 0 5 inverse 1 1 1 1 https stackoverflow com questions 20047519 python doctests test for none
from __future__ import annotations from typing import Any def add(*matrix_s: list[list[int]]) -> list[list[int]]: if all(_check_not_integer(m) for m in matrix_s): for i in matrix_s[1:]: _verify_matrix_sizes(matrix_s[0], i) return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)] raise TypeError("Expected a matrix, got int/list instead") def subtract(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: if ( _check_not_integer(matrix_a) and _check_not_integer(matrix_b) and _verify_matrix_sizes(matrix_a, matrix_b) ): return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)] raise TypeError("Expected a matrix, got int/list instead") def scalar_multiply(matrix: list[list[int]], n: float) -> list[list[float]]: return [[x * n for x in row] for row in matrix] def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) if cols[0] != rows[1]: msg = ( "Cannot multiply matrix of dimensions " f"({rows[0]},{cols[0]}) and ({rows[1]},{cols[1]})" ) raise ValueError(msg) return [ [sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a ] def identity(n: int) -> list[list[int]]: n = int(n) return [[int(row == column) for column in range(n)] for row in range(n)] def transpose( matrix: list[list[int]], return_map: bool = True ) -> list[list[int]] | map[list[int]]: if _check_not_integer(matrix): if return_map: return map(list, zip(*matrix)) else: return list(map(list, zip(*matrix))) raise TypeError("Expected a matrix, got int/list instead") def minor(matrix: list[list[int]], row: int, column: int) -> list[list[int]]: minor = matrix[:row] + matrix[row + 1 :] return [row[:column] + row[column + 1 :] for row in minor] def determinant(matrix: list[list[int]]) -> Any: if len(matrix) == 1: return matrix[0][0] return sum( x * determinant(minor(matrix, 0, i)) * (-1) ** i for i, x in enumerate(matrix[0]) ) def inverse(matrix: list[list[int]]) -> list[list[float]] | None: det = determinant(matrix) if det == 0: return None matrix_minor = [ [determinant(minor(matrix, i, j)) for j in range(len(matrix))] for i in range(len(matrix)) ] cofactors = [ [x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])] for row in range(len(matrix)) ] adjugate = list(transpose(cofactors)) return scalar_multiply(adjugate, 1 / det) def _check_not_integer(matrix: list[list[int]]) -> bool: return not isinstance(matrix, int) and not isinstance(matrix[0], int) def _shape(matrix: list[list[int]]) -> tuple[int, int]: return len(matrix), len(matrix[0]) def _verify_matrix_sizes( matrix_a: list[list[int]], matrix_b: list[list[int]] ) -> tuple[tuple[int, int], tuple[int, int]]: shape = _shape(matrix_a) + _shape(matrix_b) if shape[0] != shape[3] or shape[1] != shape[2]: msg = ( "operands could not be broadcast together with shape " f"({shape[0], shape[1]}), ({shape[2], shape[3]})" ) raise ValueError(msg) return (shape[0], shape[2]), (shape[1], shape[3]) def main() -> None: matrix_a = [[12, 10], [3, 9]] matrix_b = [[3, 4], [7, 4]] matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]] matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] print(f"Add Operation, {add(matrix_a, matrix_b) = } \n") print(f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n") print(f"Identity: {identity(5)}\n") print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n") print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n") print(f"Inverse of {matrix_d} = {inverse(matrix_d)}\n") if __name__ == "__main__": import doctest doctest.testmod() main()
given an two dimensional binary matrix grid an island is a group of 1 s representing land connected 4directionally horizontal or vertical you may assume all four edges of the grid are surrounded by water the area of an island is the number of cells with a value 1 in the island return the maximum area of an island in a grid if there is no island return 0 checking whether coordinate row col is valid or not issafe0 0 5 5 true issafe1 1 5 5 false returns the current area of the island depthfirstsearch0 0 set matrix 0 finds the area of all islands and returns the maximum area findmaxareamatrix 6 maximizing the area explanation we are allowed to move in four directions horizontal or vertical so the possible in a matrix if we are at x and y position the possible moving are directions are x y1 x y1 x1 y x1 y but we need to take care of boundary cases as well which are x and y can not be smaller than 0 and greater than the number of rows and columns respectively visualization mat 0 0 a 0 0 0 0 b 0 0 0 0 0 0 0 0 0 0 0 0 b b b 0 0 0 0 c c 0 d 0 0 0 0 0 0 0 0 0 c 0 0 d d 0 0 e 0 e 0 0 0 c 0 0 d d 0 0 e e e 0 0 0 0 0 0 0 0 0 0 0 0 e 0 0 0 0 0 0 0 0 0 f f f 0 0 0 0 0 0 0 0 0 0 f f 0 0 0 0 for visualization i have defined the connected island with letters by observation we can see that a island is of area 1 b island is of area 4 c island is of area 4 d island is of area 5 e island is of area 6 and f island is of area 5 it has 6 unique islands of mentioned areas and the maximum of all of them is 6 so we return 6 checking whether coordinate row col is valid or not is_safe 0 0 5 5 true is_safe 1 1 5 5 false returns the current area of the island depth_first_search 0 0 set matrix 0 finds the area of all islands and returns the maximum area find_max_area matrix 6 maximizing the area output 6 explanation we are allowed to move in four directions horizontal or vertical so the possible in a matrix if we are at x and y position the possible moving are directions are x y 1 x y 1 x 1 y x 1 y but we need to take care of boundary cases as well which are x and y can not be smaller than 0 and greater than the number of rows and columns respectively visualization mat 0 0 a 0 0 0 0 b 0 0 0 0 0 0 0 0 0 0 0 0 b b b 0 0 0 0 c c 0 d 0 0 0 0 0 0 0 0 0 c 0 0 d d 0 0 e 0 e 0 0 0 c 0 0 d d 0 0 e e e 0 0 0 0 0 0 0 0 0 0 0 0 e 0 0 0 0 0 0 0 0 0 f f f 0 0 0 0 0 0 0 0 0 0 f f 0 0 0 0 for visualization i have defined the connected island with letters by observation we can see that a island is of area 1 b island is of area 4 c island is of area 4 d island is of area 5 e island is of area 6 and f island is of area 5 it has 6 unique islands of mentioned areas and the maximum of all of them is 6 so we return 6
matrix = [ [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], ] def is_safe(row: int, col: int, rows: int, cols: int) -> bool: return 0 <= row < rows and 0 <= col < cols def depth_first_search(row: int, col: int, seen: set, mat: list[list[int]]) -> int: rows = len(mat) cols = len(mat[0]) if is_safe(row, col, rows, cols) and (row, col) not in seen and mat[row][col] == 1: seen.add((row, col)) return ( 1 + depth_first_search(row + 1, col, seen, mat) + depth_first_search(row - 1, col, seen, mat) + depth_first_search(row, col + 1, seen, mat) + depth_first_search(row, col - 1, seen, mat) ) else: return 0 def find_max_area(mat: list[list[int]]) -> int: seen: set = set() max_area = 0 for row, line in enumerate(mat): for col, item in enumerate(line): if item == 1 and (row, col) not in seen: max_area = max(max_area, depth_first_search(row, col, seen, mat)) return max_area if __name__ == "__main__": import doctest print(find_max_area(matrix)) doctest.testmod()
https en wikipedia orgwikimedian calculate the median of a sorted matrix args matrix a 2d matrix of integers returns the median value of the matrix examples matrix 1 3 5 2 6 9 3 6 9 medianmatrix 5 matrix 1 2 3 4 5 6 medianmatrix 3 flatten the matrix into a sorted 1d list calculate the middle index return the median calculate the median of a sorted matrix args matrix a 2d matrix of integers returns the median value of the matrix examples matrix 1 3 5 2 6 9 3 6 9 median matrix 5 matrix 1 2 3 4 5 6 median matrix 3 flatten the matrix into a sorted 1d list calculate the middle index return the median
def median(matrix: list[list[int]]) -> int: linear = sorted(num for row in matrix for num in row) mid = (len(linear) - 1) // 2 return linear[mid] if __name__ == "__main__": import doctest doctest.testmod()
implementation of finding nth fibonacci number using matrix exponentiation time complexity is about ologn8 where 8 is the complexity of matrix multiplication of size 2 by 2 and on the other hand complexity of bruteforce solution is on as we know fn fn1 fn1 converting to matrix fn fn1 1 1 1 0 fn1 fn2 fn fn1 1 1 1 02 fn2 fn3 fn fn1 1 1 1 0n1 f1 f0 so we just need the n times multiplication of the matrix 1 1 1 0 we can decrease the n times multiplication by following the divide and conquer approach nthfibonaccimatrix100 354224848179261915075 nthfibonaccimatrix100 100 nthfibonaccibruteforce100 354224848179261915075 nthfibonaccibruteforce100 100 from timeit import timeit printtimeitnthfibonaccimatrix1000000 from main import nthfibonaccimatrix number5 printtimeitnthfibonaccibruteforce1000000 from main import nthfibonaccibruteforce number5 2 3342058970001744 57 256506615000035 nth_fibonacci_matrix 100 354224848179261915075 nth_fibonacci_matrix 100 100 nth_fibonacci_bruteforce 100 354224848179261915075 nth_fibonacci_bruteforce 100 100 1000th 1000 from timeit import timeit print timeit nth_fibonacci_matrix 1000000 from main import nth_fibonacci_matrix number 5 print timeit nth_fibonacci_bruteforce 1000000 from main import nth_fibonacci_bruteforce number 5 2 3342058970001744 57 256506615000035
def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: matrix_c = [] n = len(matrix_a) for i in range(n): list_1 = [] for j in range(n): val = 0 for k in range(n): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n: int) -> list[list[int]]: return [[int(row == column) for column in range(n)] for row in range(n)] def nth_fibonacci_matrix(n: int) -> int: if n <= 1: return n res_matrix = identity(2) fibonacci_matrix = [[1, 1], [1, 0]] n = n - 1 while n > 0: if n % 2 == 1: res_matrix = multiply(res_matrix, fibonacci_matrix) fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix) n = int(n / 2) return res_matrix[0][0] def nth_fibonacci_bruteforce(n: int) -> int: if n <= 1: return n fib0 = 0 fib1 = 1 for _ in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 def main() -> None: for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): n = int("".join(c for c in ordinal if c in "0123456789")) print( f"{ordinal} fibonacci number using matrix exponentiation is " f"{nth_fibonacci_matrix(n)} and using bruteforce is " f"{nth_fibonacci_bruteforce(n)}\n" ) if __name__ == "__main__": import doctest doctest.testmod() main()
this implementation demonstrates how to generate the elements of a pascal s triangle the element havingva row index of r and column index of c can be derivedvas follows trianglerc triangler1c1triangler1c a pascal s triangle is a triangular array containing binomial coefficients https en wikipedia orgwikipascal27striangle print pascal s triangle for different number of rows printpascaltriangle5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 print left spaces print row values create pascal s triangle for different number of rows generatepascaltriangle0 generatepascaltriangle1 1 generatepascaltriangle2 1 1 1 generatepascaltriangle3 1 1 1 1 2 1 generatepascaltriangle4 1 1 1 1 2 1 1 3 3 1 generatepascaltriangle5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 generatepascaltriangle5 traceback most recent call last valueerror the input value of numrows should be greater than or equal to 0 generatepascaltriangle7 89 traceback most recent call last typeerror the input value of numrows should be int triangle 1 populatecurrentrowtriangle 1 1 1 first and last elements of current row are equal to 1 triangle 1 1 1 currentrow 1 1 1 calculatecurrentelementtriangle currentrow 2 1 currentrow 1 2 1 this function returns a matrix representing the corresponding pascal s triangle according to the given input of number of rows of pascal s triangle to be generated it reduces the operations done to generate a row by half by eliminating redundant calculations param numrows integer specifying the number of rows in the pascal s triangle return 2d list matrix representing the pascal s triangle return the pascal s triangle of given rows generatepascaltriangleoptimized3 1 1 1 1 2 1 generatepascaltriangleoptimized1 1 generatepascaltriangleoptimized0 generatepascaltriangleoptimized5 traceback most recent call last valueerror the input value of numrows should be greater than or equal to 0 generatepascaltriangleoptimized7 89 traceback most recent call last typeerror the input value of numrows should be int calculate the number of distinct elements in a row benchmark multiple functions with three different length int values printfcall 38 funcvalue timing 4f seconds print pascal s triangle for different number of rows print_pascal_triangle 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 print left spaces print row values create pascal s triangle for different number of rows generate_pascal_triangle 0 generate_pascal_triangle 1 1 generate_pascal_triangle 2 1 1 1 generate_pascal_triangle 3 1 1 1 1 2 1 generate_pascal_triangle 4 1 1 1 1 2 1 1 3 3 1 generate_pascal_triangle 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 generate_pascal_triangle 5 traceback most recent call last valueerror the input value of num_rows should be greater than or equal to 0 generate_pascal_triangle 7 89 traceback most recent call last typeerror the input value of num_rows should be int triangle 1 populate_current_row triangle 1 1 1 first and last elements of current row are equal to 1 triangle 1 1 1 current_row 1 1 1 calculate_current_element triangle current_row 2 1 current_row 1 2 1 this function returns a matrix representing the corresponding pascal s triangle according to the given input of number of rows of pascal s triangle to be generated it reduces the operations done to generate a row by half by eliminating redundant calculations param num_rows integer specifying the number of rows in the pascal s triangle return 2 d list matrix representing the pascal s triangle return the pascal s triangle of given rows generate_pascal_triangle_optimized 3 1 1 1 1 2 1 generate_pascal_triangle_optimized 1 1 generate_pascal_triangle_optimized 0 generate_pascal_triangle_optimized 5 traceback most recent call last valueerror the input value of num_rows should be greater than or equal to 0 generate_pascal_triangle_optimized 7 89 traceback most recent call last typeerror the input value of num_rows should be int calculate the number of distinct elements in a row benchmark multiple functions with three different length int values print f call 38 func value timing 4f seconds 1 7 14
def print_pascal_triangle(num_rows: int) -> None: triangle = generate_pascal_triangle(num_rows) for row_idx in range(num_rows): for _ in range(num_rows - row_idx - 1): print(end=" ") for col_idx in range(row_idx + 1): if col_idx != row_idx: print(triangle[row_idx][col_idx], end=" ") else: print(triangle[row_idx][col_idx], end="") print() def generate_pascal_triangle(num_rows: int) -> list[list[int]]: if not isinstance(num_rows, int): raise TypeError("The input value of 'num_rows' should be 'int'") if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) triangle: list[list[int]] = [] for current_row_idx in range(num_rows): current_row = populate_current_row(triangle, current_row_idx) triangle.append(current_row) return triangle def populate_current_row(triangle: list[list[int]], current_row_idx: int) -> list[int]: current_row = [-1] * (current_row_idx + 1) current_row[0], current_row[-1] = 1, 1 for current_col_idx in range(1, current_row_idx): calculate_current_element( triangle, current_row, current_row_idx, current_col_idx ) return current_row def calculate_current_element( triangle: list[list[int]], current_row: list[int], current_row_idx: int, current_col_idx: int, ) -> None: above_to_left_elt = triangle[current_row_idx - 1][current_col_idx - 1] above_to_right_elt = triangle[current_row_idx - 1][current_col_idx] current_row[current_col_idx] = above_to_left_elt + above_to_right_elt def generate_pascal_triangle_optimized(num_rows: int) -> list[list[int]]: if not isinstance(num_rows, int): raise TypeError("The input value of 'num_rows' should be 'int'") if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) result: list[list[int]] = [[1]] for row_index in range(1, num_rows): temp_row = [0] + result[-1] + [0] row_length = row_index + 1 distinct_elements = sum(divmod(row_length, 2)) row_first_half = [ temp_row[i - 1] + temp_row[i] for i in range(1, distinct_elements + 1) ] row_second_half = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() row = row_first_half + row_second_half result.append(row) return result def benchmark() -> None: from collections.abc import Callable from timeit import timeit def benchmark_a_function(func: Callable, value: int) -> None: call = f"{func.__name__}({value})" timing = timeit(f"__main__.{call}", setup="import __main__") print(f"{call:38} -- {timing:.4f} seconds") for value in range(15): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(func, value) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
in this problem we want to rotate the matrix elements by 90 180 270 counterclockwise discussion in stackoverflow https stackoverflow comquestions42519howdoyourotateatwodimensionalarray makematrix 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 makematrix1 1 makematrix2 1 2 3 4 makematrix3 1 2 3 4 5 6 7 8 9 makematrix makematrix4 true rotate90makematrix 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13 rotate90makematrix transposereversecolumnmakematrix true or transposereversecolumnmatrix rotate180makematrix 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 rotate180makematrix reversecolumnreverserowmakematrix true or reversecolumnreverserowmatrix rotate270makematrix 13 9 5 1 14 10 6 2 15 11 7 3 16 12 8 4 rotate270makematrix transposereverserowmakematrix true or transposereverserowmatrix make_matrix 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 make_matrix 1 1 make_matrix 2 1 2 3 4 make_matrix 3 1 2 3 4 5 6 7 8 9 make_matrix make_matrix 4 true rotate_90 make_matrix 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13 rotate_90 make_matrix transpose reverse_column make_matrix true or transpose reverse_column matrix rotate_180 make_matrix 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 rotate_180 make_matrix reverse_column reverse_row make_matrix true or reverse_column reverse_row matrix rotate_270 make_matrix 13 9 5 1 14 10 6 2 15 11 7 3 16 12 8 4 rotate_270 make_matrix transpose reverse_row make_matrix true or transpose reverse_row matrix
from __future__ import annotations def make_matrix(row_size: int = 4) -> list[list[int]]: row_size = abs(row_size) or 4 return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)] def rotate_90(matrix: list[list[int]]) -> list[list[int]]: return reverse_row(transpose(matrix)) def rotate_180(matrix: list[list[int]]) -> list[list[int]]: return reverse_row(reverse_column(matrix)) def rotate_270(matrix: list[list[int]]) -> list[list[int]]: return reverse_column(transpose(matrix)) def transpose(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = [list(x) for x in zip(*matrix)] return matrix def reverse_row(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = matrix[::-1] return matrix def reverse_column(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = [x[::-1] for x in matrix] return matrix def print_matrix(matrix: list[list[int]]) -> None: for i in matrix: print(*i) if __name__ == "__main__": matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_90(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_180(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_270(matrix))
searchinasortedmatrix 2 5 7 4 8 13 9 11 15 12 17 20 3 3 5 key 5 found at row 1 column 2 searchinasortedmatrix 2 5 7 4 8 13 9 11 15 12 17 20 3 3 21 key 21 not found searchinasortedmatrix 2 1 5 7 4 8 13 9 11 15 12 17 20 3 3 2 1 key 2 1 found at row 1 column 1 searchinasortedmatrix 2 1 5 7 4 8 13 9 11 15 12 17 20 3 3 2 2 key 2 2 not found search_in_a_sorted_matrix 2 5 7 4 8 13 9 11 15 12 17 20 3 3 5 key 5 found at row 1 column 2 search_in_a_sorted_matrix 2 5 7 4 8 13 9 11 15 12 17 20 3 3 21 key 21 not found search_in_a_sorted_matrix 2 1 5 7 4 8 13 9 11 15 12 17 20 3 3 2 1 key 2 1 found at row 1 column 1 search_in_a_sorted_matrix 2 1 5 7 4 8 13 9 11 15 12 17 20 3 3 2 2 key 2 2 not found
from __future__ import annotations def search_in_a_sorted_matrix(mat: list[list[int]], m: int, n: int, key: float) -> None: i, j = m - 1, 0 while i >= 0 and j < n: if key == mat[i][j]: print(f"Key {key} found at row- {i + 1} column- {j + 1}") return if key < mat[i][j]: i -= 1 else: j += 1 print(f"Key {key} not found") def main() -> None: mat = [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]] x = int(input("Enter the element to be searched:")) print(mat) search_in_a_sorted_matrix(mat, len(mat), len(mat[0]), x) if __name__ == "__main__": import doctest doctest.testmod() main()
class matrix matrix structure method matrix init initialize matrix with given size and default value example a matrix2 3 1 a matrix consist of 2 rows and 3 columns 1 1 1 1 1 1 method matrix str return string representation of this matrix prefix make string identifier make string and return method matrix validateindicies check if given indices are valid to pick element from matrix example a matrix2 6 0 a validateindices2 7 false a validateindices0 0 true method matrix getitem return arrayrowcolumn where loc row column example a matrix3 2 7 a1 0 7 method matrix setitem set arrayrowcolumn value where loc row column example a matrix2 3 1 a1 2 51 a matrix consist of 2 rows and 3 columns 1 1 1 1 1 51 method matrix add return self another example a matrix2 1 4 b matrix2 1 3 ab matrix consist of 2 rows and 1 columns 1 1 validation add method matrix neg return self example a matrix2 2 3 a0 1 a1 0 2 a matrix consist of 2 rows and 2 columns 3 2 2 3 method matrix mul return self another example a matrix2 3 1 a0 2 a1 2 3 a 2 matrix consist of 2 rows and 3 columns 2 2 6 2 2 6 method matrix transpose return selft example a matrix2 3 for r in range2 for c in range3 ar c rc a transpose matrix consist of 3 rows and 2 columns 0 0 0 1 0 2 method matrix shermanmorrison apply shermanmorrison formula in on2 to learn this formula please look this https en wikipedia orgwikishermane28093morrisonformula this method returns a uvt1 where a1 is self returns none if it s impossible to calculate warning this method doesn t check if self is invertible make sure self is invertible before execute this method example ainv matrix3 3 0 for i in range3 ainvi i 1 u matrix3 1 0 u0 0 u1 0 u2 0 1 2 3 v matrix3 1 0 v0 0 v1 0 v2 0 4 2 5 ainv shermanmorrisonu v matrix consist of 3 rows and 3 columns 1 2857142857142856 0 14285714285714285 0 3571428571428571 0 5714285714285714 0 7142857142857143 0 7142857142857142 0 8571428571428571 0 42857142857142855 0 0714285714285714 size validation calculate testing a1 u v sherman morrison class matrix matrix structure method matrix __init__ initialize matrix with given size and default value example a matrix 2 3 1 a matrix consist of 2 rows and 3 columns 1 1 1 1 1 1 method matrix __str__ return string representation of this matrix prefix make string identifier make string and return method matrix validate_indicies check if given indices are valid to pick element from matrix example a matrix 2 6 0 a validate_indices 2 7 false a validate_indices 0 0 true method matrix __getitem__ return array row column where loc row column example a matrix 3 2 7 a 1 0 7 method matrix __setitem__ set array row column value where loc row column example a matrix 2 3 1 a 1 2 51 a matrix consist of 2 rows and 3 columns 1 1 1 1 1 51 method matrix __add__ return self another example a matrix 2 1 4 b matrix 2 1 3 a b matrix consist of 2 rows and 1 columns 1 1 validation add method matrix __neg__ return self example a matrix 2 2 3 a 0 1 a 1 0 2 a matrix consist of 2 rows and 2 columns 3 2 2 3 method matrix __mul__ return self another example a matrix 2 3 1 a 0 2 a 1 2 3 a 2 matrix consist of 2 rows and 3 columns 2 2 6 2 2 6 scalar multiplication matrix multiplication method matrix transpose return self t example a matrix 2 3 for r in range 2 for c in range 3 a r c r c a transpose matrix consist of 3 rows and 2 columns 0 0 0 1 0 2 method matrix sherman_morrison apply sherman morrison formula in o n 2 to learn this formula please look this https en wikipedia org wiki sherman e2 80 93morrison_formula this method returns a uv t 1 where a 1 is self returns none if it s impossible to calculate warning this method doesn t check if self is invertible make sure self is invertible before execute this method example ainv matrix 3 3 0 for i in range 3 ainv i i 1 u matrix 3 1 0 u 0 0 u 1 0 u 2 0 1 2 3 v matrix 3 1 0 v 0 0 v 1 0 v 2 0 4 2 5 ainv sherman_morrison u v matrix consist of 3 rows and 3 columns 1 2857142857142856 0 14285714285714285 0 3571428571428571 0 5714285714285714 0 7142857142857143 0 7142857142857142 0 8571428571428571 0 42857142857142855 0 0714285714285714 size validation u v should be column vector u v should be column vector calculate it s not invertible testing a 1 u v sherman morrison
from __future__ import annotations from typing import Any class Matrix: def __init__(self, row: int, column: int, default_value: float = 0) -> None: self.row, self.column = row, column self.array = [[default_value for _ in range(column)] for _ in range(row)] def __str__(self) -> str: s = f"Matrix consist of {self.row} rows and {self.column} columns\n" max_element_length = 0 for row_vector in self.array: for obj in row_vector: max_element_length = max(max_element_length, len(str(obj))) string_format_identifier = f"%{max_element_length}s" def single_line(row_vector: list[float]) -> str: nonlocal string_format_identifier line = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(row_vector) for row_vector in self.array) return s def __repr__(self) -> str: return str(self) def validate_indices(self, loc: tuple[int, int]) -> bool: if not (isinstance(loc, (list, tuple)) and len(loc) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self, loc: tuple[int, int]) -> Any: assert self.validate_indices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple[int, int], value: float) -> None: assert self.validate_indices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another: Matrix) -> Matrix: assert isinstance(another, Matrix) assert self.row == another.row assert self.column == another.column result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] + another[r, c] return result def __neg__(self) -> Matrix: result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = -self[r, c] return result def __sub__(self, another: Matrix) -> Matrix: return self + (-another) def __mul__(self, another: float | Matrix) -> Matrix: if isinstance(another, (int, float)): result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] * another return result elif isinstance(another, Matrix): assert self.column == another.row result = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: msg = f"Unsupported type given for another ({type(another)})" raise TypeError(msg) def transpose(self) -> Matrix: result = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): result[c, r] = self[r, c] return result def sherman_morrison(self, u: Matrix, v: Matrix) -> Any: assert isinstance(u, Matrix) assert isinstance(v, Matrix) assert self.row == self.column == u.row == v.row assert u.column == v.column == 1 v_t = v.transpose() numerator_factor = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) if __name__ == "__main__": def test1() -> None: ainv = Matrix(3, 3, 0) for i in range(3): ainv[i, i] = 1 print(f"a^(-1) is {ainv}") u = Matrix(3, 1, 0) u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 print(f"u is {u}") print(f"v is {v}") print(f"uv^T is {u * v.transpose()}") print(f"(a + uv^T)^(-1) is {ainv.sherman_morrison(u, v)}") def test2() -> None: import doctest doctest.testmod() test2()
this program print the matrix in spiral form this problem has been solved through recursive way matrix must satisfy below conditions i matrix should be only one or two dimensional ii number of column of all rows should be equal must be spiralprintclockwise1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 8 12 11 10 9 5 6 7 horizotal printing increasing vertical printing down horizotal printing decreasing vertical printing up other easy to understand approach spiraltraversal1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 8 12 11 10 9 5 6 7 example matrix 1 2 3 4 5 6 7 8 9 10 11 12 algorithm step 1 first pop the 0 index list which is 1 2 3 4 and concatenate the output of step 2 step 2 now perform matrixs transpose operation change rows to column and vice versa and reverse the resultant matrix step 3 pass the output of 2nd step to same recursive function till base case hits dry run stage 1 1 2 3 4 spiraltraversal 8 12 7 11 6 10 5 9 stage 2 1 2 3 4 8 12 spiraltraversal 11 10 9 7 6 5 stage 3 1 2 3 4 8 12 11 10 9 spiraltraversal 5 6 7 stage 4 1 2 3 4 8 12 11 10 9 5 spiraltraversal 5 6 7 stage 5 1 2 3 4 8 12 11 10 9 5 spiraltraversal6 7 stage 6 1 2 3 4 8 12 11 10 9 5 6 7 spiraltraversal driver code must be spiral_print_clockwise 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 8 12 11 10 9 5 6 7 horizotal printing increasing vertical printing down horizotal printing decreasing vertical printing up other easy to understand approach spiral_traversal 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 8 12 11 10 9 5 6 7 example matrix 1 2 3 4 5 6 7 8 9 10 11 12 algorithm step 1 first pop the 0 index list which is 1 2 3 4 and concatenate the output of step 2 step 2 now perform matrix s transpose operation change rows to column and vice versa and reverse the resultant matrix step 3 pass the output of 2nd step to same recursive function till base case hits dry run stage 1 1 2 3 4 spiral_traversal 8 12 7 11 6 10 5 9 stage 2 1 2 3 4 8 12 spiral_traversal 11 10 9 7 6 5 stage 3 1 2 3 4 8 12 11 10 9 spiral_traversal 5 6 7 stage 4 1 2 3 4 8 12 11 10 9 5 spiral_traversal 5 6 7 stage 5 1 2 3 4 8 12 11 10 9 5 spiral_traversal 6 7 stage 6 1 2 3 4 8 12 11 10 9 5 6 7 spiral_traversal type ignore driver code
def check_matrix(matrix: list[list[int]]) -> bool: matrix = [list(row) for row in matrix] if matrix and isinstance(matrix, list): if isinstance(matrix[0], list): prev_len = 0 for row in matrix: if prev_len == 0: prev_len = len(row) result = True else: result = prev_len == len(row) else: result = True else: result = False return result def spiral_print_clockwise(a: list[list[int]]) -> None: if check_matrix(a) and len(a) > 0: a = [list(row) for row in a] mat_row = len(a) if isinstance(a[0], list): mat_col = len(a[0]) else: for dat in a: print(dat) return for i in range(mat_col): print(a[0][i]) for i in range(1, mat_row): print(a[i][mat_col - 1]) if mat_row > 1: for i in range(mat_col - 2, -1, -1): print(a[mat_row - 1][i]) for i in range(mat_row - 2, 0, -1): print(a[i][0]) remain_mat = [row[1 : mat_col - 1] for row in a[1 : mat_row - 1]] if len(remain_mat) > 0: spiral_print_clockwise(remain_mat) else: return else: print("Not a valid matrix") return def spiral_traversal(matrix: list[list]) -> list[int]: if matrix: return list(matrix.pop(0)) + spiral_traversal(list(zip(*matrix))[::-1]) else: return [] if __name__ == "__main__": import doctest doctest.testmod() a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] spiral_print_clockwise(a)
testing here assumes that numpy and linalg is always correct if running from pycharm you can place the following line in additional arguments for the pytest run configuration vv m matops p no cacheprovider standard libraries customlocal libraries standard libraries type ignore custom local libraries
import logging import sys import numpy as np import pytest from matrix import matrix_operation as matop mat_a = [[12, 10], [3, 9]] mat_b = [[3, 4], [7, 4]] mat_c = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] mat_d = [[3, 0, -2], [2, 0, 2], [0, 1, 1]] mat_e = [[3, 0, 2], [2, 0, -2], [0, 1, 1], [2, 0, -2]] mat_f = [1] mat_h = [2] logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @pytest.mark.mat_ops() @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_addition(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_addition.__name__} returned integer") with pytest.raises(TypeError): matop.add(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_addition.__name__} with same matrix dims") act = (np.array(mat1) + np.array(mat2)).tolist() theo = matop.add(mat1, mat2) assert theo == act else: logger.info(f"\n\t{test_addition.__name__} with different matrix dims") with pytest.raises(ValueError): matop.add(mat1, mat2) @pytest.mark.mat_ops() @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_subtraction(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_subtraction.__name__} returned integer") with pytest.raises(TypeError): matop.subtract(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_subtraction.__name__} with same matrix dims") act = (np.array(mat1) - np.array(mat2)).tolist() theo = matop.subtract(mat1, mat2) assert theo == act else: logger.info(f"\n\t{test_subtraction.__name__} with different matrix dims") with pytest.raises(ValueError): assert matop.subtract(mat1, mat2) @pytest.mark.mat_ops() @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_multiplication(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_multiplication.__name__} returned integer") with pytest.raises(TypeError): matop.add(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_multiplication.__name__} meets dim requirements") act = (np.matmul(mat1, mat2)).tolist() theo = matop.multiply(mat1, mat2) assert theo == act else: logger.info( f"\n\t{test_multiplication.__name__} does not meet dim requirements" ) with pytest.raises(ValueError): assert matop.subtract(mat1, mat2) @pytest.mark.mat_ops() def test_scalar_multiply(): act = (3.5 * np.array(mat_a)).tolist() theo = matop.scalar_multiply(mat_a, 3.5) assert theo == act @pytest.mark.mat_ops() def test_identity(): act = (np.identity(5)).tolist() theo = matop.identity(5) assert theo == act @pytest.mark.mat_ops() @pytest.mark.parametrize("mat", [mat_a, mat_b, mat_c, mat_d, mat_e, mat_f]) def test_transpose(mat): if (np.array(mat)).shape < (2, 2): logger.info(f"\n\t{test_transpose.__name__} returned integer") with pytest.raises(TypeError): matop.transpose(mat) else: act = (np.transpose(mat)).tolist() theo = matop.transpose(mat, return_map=False) assert theo == act
leetcode 36 valid sudoku https leetcode comproblemsvalidsudoku https en wikipedia orgwikisudoku determine if a 9 x 9 sudoku board is valid only the filled cells need to be validated according to the following rules each row must contain the digits 19 without repetition each column must contain the digits 19 without repetition each of the nine 3 x 3 subboxes of the grid must contain the digits 19 without repetition note a sudoku board partially filled could be valid but is not necessarily solvable only the filled cells need to be validated according to the mentioned rules this function validates but does not solve a sudoku board the board may be valid but unsolvable isvalidsudokuboard 5 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 2 8 4 1 9 5 8 7 9 true isvalidsudokuboard 8 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 2 8 4 1 9 5 8 7 9 false isvalidsudokuboard 1 2 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 true isvalidsudokuboard 1 2 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 true isvalidsudokuboard 1 2 3 5 6 4 4 5 6 8 9 7 7 8 9 2 3 1 4 5 6 7 8 9 1 2 3 3 1 2 7 8 9 6 4 5 1 2 3 9 7 8 4 5 6 true isvalidsudokuboard 1 2 3 4 5 6 7 8 9 2 8 3 7 4 6 5 5 6 4 7 3 8 2 9 8 7 6 5 4 3 2 1 false isvalidsudokuboard 1 2 3 8 9 7 5 6 4 4 5 6 2 3 1 8 9 7 7 8 9 5 6 4 2 3 1 2 3 1 4 5 6 9 7 8 5 6 4 7 8 9 3 1 2 8 9 7 1 2 3 6 4 5 3 1 2 6 4 5 7 8 9 6 4 5 9 7 8 1 2 3 9 7 8 3 1 2 4 5 6 true isvalidsudokuboard1 2 3 4 5 6 7 8 9 traceback most recent call last valueerror sudoku boards must be 9x9 squares isvalidsudokuboard 1 2 3 4 5 6 7 8 9 traceback most recent call last valueerror sudoku boards must be 9x9 squares this function validates but does not solve a sudoku board the board may be valid but unsolvable is_valid_sudoku_board 5 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 2 8 4 1 9 5 8 7 9 true is_valid_sudoku_board 8 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 2 8 4 1 9 5 8 7 9 false is_valid_sudoku_board 1 2 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 true is_valid_sudoku_board 1 2 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 true is_valid_sudoku_board 1 2 3 5 6 4 4 5 6 8 9 7 7 8 9 2 3 1 4 5 6 7 8 9 1 2 3 3 1 2 7 8 9 6 4 5 1 2 3 9 7 8 4 5 6 true is_valid_sudoku_board 1 2 3 4 5 6 7 8 9 2 8 3 7 4 6 5 5 6 4 7 3 8 2 9 8 7 6 5 4 3 2 1 false is_valid_sudoku_board 1 2 3 8 9 7 5 6 4 4 5 6 2 3 1 8 9 7 7 8 9 5 6 4 2 3 1 2 3 1 4 5 6 9 7 8 5 6 4 7 8 9 3 1 2 8 9 7 1 2 3 6 4 5 3 1 2 6 4 5 7 8 9 6 4 5 9 7 8 1 2 3 9 7 8 3 1 2 4 5 6 true is_valid_sudoku_board 1 2 3 4 5 6 7 8 9 traceback most recent call last valueerror sudoku boards must be 9x9 squares is_valid_sudoku_board 1 2 3 4 5 6 7 8 9 traceback most recent call last valueerror sudoku boards must be 9x9 squares
from collections import defaultdict NUM_SQUARES = 9 EMPTY_CELL = "." def is_valid_sudoku_board(sudoku_board: list[list[str]]) -> bool: if len(sudoku_board) != NUM_SQUARES or ( any(len(row) != NUM_SQUARES for row in sudoku_board) ): error_message = f"Sudoku boards must be {NUM_SQUARES}x{NUM_SQUARES} squares." raise ValueError(error_message) row_values: defaultdict[int, set[str]] = defaultdict(set) col_values: defaultdict[int, set[str]] = defaultdict(set) box_values: defaultdict[tuple[int, int], set[str]] = defaultdict(set) for row in range(NUM_SQUARES): for col in range(NUM_SQUARES): value = sudoku_board[row][col] if value == EMPTY_CELL: continue box = (row // 3, col // 3) if ( value in row_values[row] or value in col_values[col] or value in box_values[box] ): return False row_values[row].add(value) col_values[col].add(value) box_values[box].add(value) return True if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(timeit("is_valid_sudoku_board(valid_board)", globals=globals())) print(timeit("is_valid_sudoku_board(invalid_board)", globals=globals()))
fordfulkerson algorithm for maximum flow problem https en wikipedia orgwikiforde28093fulkersonalgorithm description 1 start with initial flow as 0 2 choose the augmenting path from source to sink and add the path to flow this function returns true if there is a node that has not iterated args graph adjacency matrix of graph source source sink sink parents parent list returns true if there is a node that has not iterated breadthfirstsearchgraph 0 5 1 1 1 1 1 1 true breadthfirstsearchgraph 0 6 1 1 1 1 1 1 traceback most recent call last indexerror list index out of range source node traverse all adjacent nodes of u this function returns the maximum flow from source to sink in the given graph caution this function changes the given graph args graph adjacency matrix of graph source source sink sink returns maximum flow testgraph 0 16 13 0 0 0 0 0 10 12 0 0 0 4 0 0 14 0 0 0 9 0 0 20 0 0 0 7 0 4 0 0 0 0 0 0 fordfulkersontestgraph 0 5 23 this array is filled by breadthfirst search and to store path while there is a path from source to sink find the minimum value in the selected path this function returns true if there is a node that has not iterated args graph adjacency matrix of graph source source sink sink parents parent list returns true if there is a node that has not iterated breadth_first_search graph 0 5 1 1 1 1 1 1 true breadth_first_search graph 0 6 1 1 1 1 1 1 traceback most recent call last indexerror list index out of range mark all nodes as not visited breadth first search queue source node pop the front node traverse all adjacent nodes of u this function returns the maximum flow from source to sink in the given graph caution this function changes the given graph args graph adjacency matrix of graph source source sink sink returns maximum flow test_graph 0 16 13 0 0 0 0 0 10 12 0 0 0 4 0 0 14 0 0 0 9 0 0 20 0 0 0 7 0 4 0 0 0 0 0 0 ford_fulkerson test_graph 0 5 23 this array is filled by breadth first search and to store path while there is a path from source to sink infinite value find the minimum value in the selected path
graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def breadth_first_search(graph: list, source: int, sink: int, parents: list) -> bool: visited = [False] * len(graph) queue = [] queue.append(source) visited[source] = True while queue: u = queue.pop(0) for ind, node in enumerate(graph[u]): if visited[ind] is False and node > 0: queue.append(ind) visited[ind] = True parents[ind] = u return visited[sink] def ford_fulkerson(graph: list, source: int, sink: int) -> int: parent = [-1] * (len(graph)) max_flow = 0 while breadth_first_search(graph, source, sink, parent): path_flow = int(1e9) s = sink while s != source: path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] return max_flow if __name__ == "__main__": from doctest import testmod testmod() print(f"{ford_fulkerson(graph, source=0, sink=5) = }")
minimum cut on fordfulkerson algorithm return true if there is node that has not iterated this array is filled by bfs and to store path mincuttestgraph source0 sink5 1 3 4 3 4 5 find the minimum value in select path minimum cut on ford_fulkerson algorithm return true if there is node that has not iterated this array is filled by bfs and to store path mincut test_graph source 0 sink 5 1 3 4 3 4 5 record original cut copy find the minimum value in select path
test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def bfs(graph, s, t, parent): visited = [False] * len(graph) queue = [s] visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return visited[t] def mincut(graph, source, sink): parent = [-1] * (len(graph)) max_flow = 0 res = [] temp = [i[:] for i in graph] while bfs(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j)) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
references http neuralnetworksanddeeplearning comchap2 html backpropagation https en wikipedia orgwikisigmoidfunction sigmoid activation function https en wikipedia orgwikifeedforwardneuralnetwork feedforward this function initializes the twohiddenlayerneuralnetwork class with random weights for every layer and initializes predicted output with zeroes inputarray input values for training the neural network i e training data outputarray expected output values of the given inputs input values provided for training the model random initial weights are assigned where first argument is the number of nodes in previous layer and second argument is the number of nodes in the next layer random initial weights are assigned self inputarray shape1 is used to represent number of nodes in input layer first hidden layer consists of 4 nodes random initial values for the first hidden layer first hidden layer has 4 nodes second hidden layer has 3 nodes random initial values for the second hidden layer second hidden layer has 3 nodes output layer has 1 node real output values provided predicted output values by the neural network predictedoutput array initially consists of zeroes the information moves in only one direction i e forward from the input nodes through the two hidden nodes and to the output nodes there are no cycles or loops in the network return layerbetweensecondhiddenlayerandoutput i e the last layer of the neural network inputval numpy array0 0 0 0 0 0 0 0 0 dtypefloat outputval numpy array0 0 0 dtypefloat nn twohiddenlayerneuralnetworkinputval outputval res nn feedforward arraysum numpy sumres numpy isnanarraysum false layerbetweeninputandfirsthiddenlayer is the layer connecting the input nodes with the first hidden layer nodes layerbetweenfirsthiddenlayerandsecondhiddenlayer is the layer connecting the first hidden set of nodes with the second hidden set of nodes layerbetweensecondhiddenlayerandoutput is the layer connecting second hidden layer with the output node function for finetuning the weights of the neural net based on the error rate obtained in the previous epoch i e iteration updation is done using derivative of sogmoid activation function inputval numpy array0 0 0 0 0 0 0 0 0 dtypefloat outputval numpy array0 0 0 dtypefloat nn twohiddenlayerneuralnetworkinputval outputval res nn feedforward nn backpropagation updatedweights nn secondhiddenlayerandoutputlayerweights res updatedweights all false performs the feedforwarding and back propagation process for the given number of iterations every iteration will update the weights of neural network output real output values required for calculating loss iterations number of times the weights are to be updated giveloss boolean value if true then prints loss for each iteration if false then nothing is printed inputval numpy array0 0 0 0 1 0 0 0 1 dtypefloat outputval numpy array0 1 1 dtypefloat nn twohiddenlayerneuralnetworkinputval outputval firstiterationweights nn feedforward nn backpropagation updatedweights nn secondhiddenlayerandoutputlayerweights firstiterationweights updatedweights all false predict s the output for the given input values using the trained neural network the output value given by the model ranges inbetween 0 and 1 the predict function returns 1 if the model value is greater than the threshold value else returns 0 as the real output values are in binary inputval numpy array0 0 0 0 1 0 0 0 1 dtypefloat outputval numpy array0 1 1 dtypefloat nn twohiddenlayerneuralnetworkinputval outputval nn trainoutputval 1000 false nn predict0 1 0 in 0 1 true input values for which the predictions are to be made applies sigmoid activation function return normalized values sigmoidnumpy array1 0 2 1 0 0 dtypenumpy float64 array0 73105858 0 5 0 88079708 0 73105858 0 5 0 5 provides the derivative value of the sigmoid function returns derivative of the sigmoid value sigmoidderivativenumpy array1 0 2 1 0 0 dtypenumpy float64 array 0 0 2 0 0 0 example for how to use the neural network class and use the respected methods for the desired output calls the twohiddenlayerneuralnetwork class and provides the fixed input output values to the model model is trained for a fixed amount of iterations then the predict method is called in this example the output is divided into 2 classes i e binary classification the two classes are represented by 0 and 1 example in 0 1 true input values true output values for the given input values calling neural network class calling training function set giveloss to true if you want to see loss in every iteration this function initializes the twohiddenlayerneuralnetwork class with random weights for every layer and initializes predicted output with zeroes input_array input values for training the neural network i e training data output_array expected output values of the given inputs input values provided for training the model random initial weights are assigned where first argument is the number of nodes in previous layer and second argument is the number of nodes in the next layer random initial weights are assigned self input_array shape 1 is used to represent number of nodes in input layer first hidden layer consists of 4 nodes random initial values for the first hidden layer first hidden layer has 4 nodes second hidden layer has 3 nodes random initial values for the second hidden layer second hidden layer has 3 nodes output layer has 1 node real output values provided predicted output values by the neural network predicted_output array initially consists of zeroes the information moves in only one direction i e forward from the input nodes through the two hidden nodes and to the output nodes there are no cycles or loops in the network return layer_between_second_hidden_layer_and_output i e the last layer of the neural network input_val numpy array 0 0 0 0 0 0 0 0 0 dtype float output_val numpy array 0 0 0 dtype float nn twohiddenlayerneuralnetwork input_val output_val res nn feedforward array_sum numpy sum res numpy isnan array_sum false layer_between_input_and_first_hidden_layer is the layer connecting the input nodes with the first hidden layer nodes layer_between_first_hidden_layer_and_second_hidden_layer is the layer connecting the first hidden set of nodes with the second hidden set of nodes layer_between_second_hidden_layer_and_output is the layer connecting second hidden layer with the output node function for fine tuning the weights of the neural net based on the error rate obtained in the previous epoch i e iteration updation is done using derivative of sogmoid activation function input_val numpy array 0 0 0 0 0 0 0 0 0 dtype float output_val numpy array 0 0 0 dtype float nn twohiddenlayerneuralnetwork input_val output_val res nn feedforward nn back_propagation updated_weights nn second_hidden_layer_and_output_layer_weights res updated_weights all false performs the feedforwarding and back propagation process for the given number of iterations every iteration will update the weights of neural network output real output values required for calculating loss iterations number of times the weights are to be updated give_loss boolean value if true then prints loss for each iteration if false then nothing is printed input_val numpy array 0 0 0 0 1 0 0 0 1 dtype float output_val numpy array 0 1 1 dtype float nn twohiddenlayerneuralnetwork input_val output_val first_iteration_weights nn feedforward nn back_propagation updated_weights nn second_hidden_layer_and_output_layer_weights first_iteration_weights updated_weights all false predict s the output for the given input values using the trained neural network the output value given by the model ranges in between 0 and 1 the predict function returns 1 if the model value is greater than the threshold value else returns 0 as the real output values are in binary input_val numpy array 0 0 0 0 1 0 0 0 1 dtype float output_val numpy array 0 1 1 dtype float nn twohiddenlayerneuralnetwork input_val output_val nn train output_val 1000 false nn predict 0 1 0 in 0 1 true input values for which the predictions are to be made applies sigmoid activation function return normalized values sigmoid numpy array 1 0 2 1 0 0 dtype numpy float64 array 0 73105858 0 5 0 88079708 0 73105858 0 5 0 5 provides the derivative value of the sigmoid function returns derivative of the sigmoid value sigmoid_derivative numpy array 1 0 2 1 0 0 dtype numpy float64 array 0 0 2 0 0 0 example for how to use the neural network class and use the respected methods for the desired output calls the twohiddenlayerneuralnetwork class and provides the fixed input output values to the model model is trained for a fixed amount of iterations then the predict method is called in this example the output is divided into 2 classes i e binary classification the two classes are represented by 0 and 1 example in 0 1 true input values true output values for the given input values calling neural network class calling training function set give_loss to true if you want to see loss in every iteration
import numpy class TwoHiddenLayerNeuralNetwork: def __init__(self, input_array: numpy.ndarray, output_array: numpy.ndarray) -> None: self.input_array = input_array self.input_layer_and_first_hidden_layer_weights = numpy.random.rand( self.input_array.shape[1], 4 ) self.first_hidden_layer_and_second_hidden_layer_weights = numpy.random.rand( 4, 3 ) self.second_hidden_layer_and_output_layer_weights = numpy.random.rand(3, 1) self.output_array = output_array self.predicted_output = numpy.zeros(output_array.shape) def feedforward(self) -> numpy.ndarray: self.layer_between_input_and_first_hidden_layer = sigmoid( numpy.dot(self.input_array, self.input_layer_and_first_hidden_layer_weights) ) self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights, ) ) self.layer_between_second_hidden_layer_and_output = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights, ) ) return self.layer_between_second_hidden_layer_and_output def back_propagation(self) -> None: updated_second_hidden_layer_and_output_layer_weights = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T, 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), ) updated_first_hidden_layer_and_second_hidden_layer_weights = numpy.dot( self.layer_between_input_and_first_hidden_layer.T, numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), self.second_hidden_layer_and_output_layer_weights.T, ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ), ) updated_input_layer_and_first_hidden_layer_weights = numpy.dot( self.input_array.T, numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), self.second_hidden_layer_and_output_layer_weights.T, ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ), self.first_hidden_layer_and_second_hidden_layer_weights.T, ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer), ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def train(self, output: numpy.ndarray, iterations: int, give_loss: bool) -> None: for iteration in range(1, iterations + 1): self.output = self.feedforward() self.back_propagation() if give_loss: loss = numpy.mean(numpy.square(output - self.feedforward())) print(f"Iteration {iteration} Loss: {loss}") def predict(self, input_arr: numpy.ndarray) -> int: self.array = input_arr self.layer_between_input_and_first_hidden_layer = sigmoid( numpy.dot(self.array, self.input_layer_and_first_hidden_layer_weights) ) self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights, ) ) self.layer_between_second_hidden_layer_and_output = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights, ) ) return int((self.layer_between_second_hidden_layer_and_output > 0.6)[0]) def sigmoid(value: numpy.ndarray) -> numpy.ndarray: return 1 / (1 + numpy.exp(-value)) def sigmoid_derivative(value: numpy.ndarray) -> numpy.ndarray: return (value) * (1 - (value)) def example() -> int: test_input = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ), dtype=numpy.float64, ) output = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=numpy.float64) neural_network = TwoHiddenLayerNeuralNetwork( input_array=test_input, output_array=output ) neural_network.train(output=output, iterations=10, give_loss=False) return neural_network.predict(numpy.array(([1, 1, 1]), dtype=numpy.float64)) if __name__ == "__main__": example()
this script demonstrates the implementation of the binary step function it s an activation function in which the neuron is activated if the input is positive or 0 else it is deactivated it s a simple activation function which is mentioned in this wikipedia article https en wikipedia orgwikiactivationfunction implements the binary step function parameters vector ndarray a vector that consists of numeric values returns vector ndarray input vector after applying binary step function vector np array1 2 0 2 1 45 3 7 0 3 binarystepvector array0 1 1 1 0 1 implements the binary step function parameters vector ndarray a vector that consists of numeric values returns vector ndarray input vector after applying binary step function vector np array 1 2 0 2 1 45 3 7 0 3 binary_step vector array 0 1 1 1 0 1
import numpy as np def binary_step(vector: np.ndarray) -> np.ndarray: return np.where(vector >= 0, 1, 0) if __name__ == "__main__": import doctest doctest.testmod()
implements the exponential linear unit or elu function the function takes a vector of k real numbers and a real number alpha as input and then applies the elu function to each element of the vector script inspired from its corresponding wikipedia article https en wikipedia orgwikirectifierneuralnetworks implements the elu activation function parameters vector the array containing input of elu activation alpha hyperparameter return elu np array the input numpy array after applying elu mathematically fx x x0 else alpha ex 1 x0 alpha 0 examples exponentiallinearunitvectornp array2 3 0 6 2 3 8 alpha0 3 array 2 3 0 6 0 25939942 0 29328877 exponentiallinearunitvectornp array9 2 0 3 0 45 4 56 alpha0 067 array0 06699323 0 01736518 0 45 0 06629904 implements the elu activation function parameters vector the array containing input of elu activation alpha hyper parameter return elu np array the input numpy array after applying elu mathematically f x x x 0 else alpha e x 1 x 0 alpha 0 examples exponential_linear_unit vector np array 2 3 0 6 2 3 8 alpha 0 3 array 2 3 0 6 0 25939942 0 29328877 exponential_linear_unit vector np array 9 2 0 3 0 45 4 56 alpha 0 067 array 0 06699323 0 01736518 0 45 0 06629904
import numpy as np def exponential_linear_unit(vector: np.ndarray, alpha: float) -> np.ndarray: return np.where(vector > 0, vector, (alpha * (np.exp(vector) - 1))) if __name__ == "__main__": import doctest doctest.testmod()
leaky rectified linear unit leaky relu use case leaky relu addresses the problem of the vanishing gradient for more detailed information you can refer to the following link https en wikipedia orgwikirectifierneuralnetworksleakyrelu implements the leakyrelu activation function parameters vector np ndarray the input array for leakyrelu activation alpha float the slope for negative values returns np ndarray the input array after applying the leakyrelu activation formula fx x if x 0 else fx alpha x examples leakyrectifiedlinearunitvectornp array2 3 0 6 2 3 8 alpha0 3 array 2 3 0 6 0 6 1 14 leakyrectifiedlinearunitnp array9 2 0 3 0 45 4 56 alpha0 067 array0 6164 0 0201 0 45 0 30552 implements the leakyrelu activation function parameters vector np ndarray the input array for leakyrelu activation alpha float the slope for negative values returns np ndarray the input array after applying the leakyrelu activation formula f x x if x 0 else f x alpha x examples leaky_rectified_linear_unit vector np array 2 3 0 6 2 3 8 alpha 0 3 array 2 3 0 6 0 6 1 14 leaky_rectified_linear_unit np array 9 2 0 3 0 45 4 56 alpha 0 067 array 0 6164 0 0201 0 45 0 30552
import numpy as np def leaky_rectified_linear_unit(vector: np.ndarray, alpha: float) -> np.ndarray: return np.where(vector > 0, vector, alpha * vector) if __name__ == "__main__": import doctest doctest.testmod()
mish activation function use case improved version of the relu activation function used in computer vision for more detailed information you can refer to the following link https en wikipedia orgwikirectifierneuralnetworksmish implements the mish activation function parameters vector np ndarray the input array for mish activation returns np ndarray the input array after applying the mish activation formula fx x tanhsoftplusx x tanhln1 ex examples mishvectornp array2 3 0 6 2 3 8 array 2 26211893 0 46613649 0 25250148 0 08405831 mishnp array9 2 0 3 0 45 4 56 array0 00092952 0 15113318 0 33152014 0 04745745 implements the mish activation function parameters vector np ndarray the input array for mish activation returns np ndarray the input array after applying the mish activation formula f x x tanh softplus x x tanh ln 1 e x examples mish vector np array 2 3 0 6 2 3 8 array 2 26211893 0 46613649 0 25250148 0 08405831 mish np array 9 2 0 3 0 45 4 56 array 0 00092952 0 15113318 0 33152014 0 04745745
import numpy as np from softplus import softplus def mish(vector: np.ndarray) -> np.ndarray: return vector * np.tanh(softplus(vector)) if __name__ == "__main__": import doctest doctest.testmod()
this script demonstrates the implementation of the relu function it s a kind of activation function defined as the positive part of its argument in the context of neural network the function takes a vector of k real numbers as input and then argmaxx 0 after through relu the element of the vector always 0 or real number script inspired from its corresponding wikipedia article https en wikipedia orgwikirectifierneuralnetworks implements the relu function parameters vector np array list tuple a numpy array of shape 1 n consisting of real values or a similar list tuple returns reluvec np array the input numpy array after applying relu vec np array1 0 5 reluvec array0 0 5 compare two arrays and then return elementwise maxima implements the relu function parameters vector np array list tuple a numpy array of shape 1 n consisting of real values or a similar list tuple returns relu_vec np array the input numpy array after applying relu vec np array 1 0 5 relu vec array 0 0 5 compare two arrays and then return element wise maxima 0 0 5
from __future__ import annotations import numpy as np def relu(vector: list[float]): return np.maximum(0, vector) if __name__ == "__main__": print(np.array(relu([-1, 0, 5])))
implements the scaled exponential linear unit or selu function the function takes a vector of k real numbers and two real numbers alphadefault 1 6732 lambda default 1 0507 as input and then applies the selu function to each element of the vector selu is a selfnormalizing activation function it is a variant of the elu the main advantage of selu is that we can be sure that the output will always be standardized due to its selfnormalizing behavior that means there is no need to include batchnormalization layers references https iq opengenus orgscaledexponentiallinearunit applies the scaled exponential linear unit function to each element of the vector parameters vector np ndarray alpha float default 1 6732 lambda float default 1 0507 returns np ndarray formula fx lambda x if x 0 lambda alpha ex 1 if x 0 examples scaledexponentiallinearunitvectornp array1 3 3 7 2 4 array1 36591 3 88759 2 52168 scaledexponentiallinearunitvectornp array1 3 4 7 8 2 array1 36591 4 93829 8 61574 applies the scaled exponential linear unit function to each element of the vector parameters vector np ndarray alpha float default 1 6732 lambda_ float default 1 0507 returns np ndarray formula f x lambda_ x if x 0 lambda_ alpha e x 1 if x 0 examples scaled_exponential_linear_unit vector np array 1 3 3 7 2 4 array 1 36591 3 88759 2 52168 scaled_exponential_linear_unit vector np array 1 3 4 7 8 2 array 1 36591 4 93829 8 61574
import numpy as np def scaled_exponential_linear_unit( vector: np.ndarray, alpha: float = 1.6732, lambda_: float = 1.0507 ) -> np.ndarray: return lambda_ * np.where(vector > 0, vector, alpha * (np.exp(vector) - 1)) if __name__ == "__main__": import doctest doctest.testmod()
this script implements the soboleva modified hyperbolic tangent function the function applies the soboleva modified hyperbolic tangent function to each element of the vector more details about the activation function can be found on https en wikipedia orgwikisobolevamodifiedhyperbolictangent implements the soboleva modified hyperbolic tangent function parameters vector ndarray a vector that consists of numeric values avalue float parameter a of the equation bvalue float parameter b of the equation cvalue float parameter c of the equation dvalue float parameter d of the equation returns vector ndarray input array after applying smht function vector np array5 4 2 4 6 3 5 23 3 27 0 56 sobolevamodifiedhyperbolictangentvector 0 2 0 4 0 6 0 8 array 0 11075085 0 28236685 0 07861169 0 1180085 0 22999056 0 1566043 separate the numerator and denominator for simplicity calculate the numerator and denominator elementwise calculate and return the final result elementwise implements the soboleva modified hyperbolic tangent function parameters vector ndarray a vector that consists of numeric values a_value float parameter a of the equation b_value float parameter b of the equation c_value float parameter c of the equation d_value float parameter d of the equation returns vector ndarray input array after applying smht function vector np array 5 4 2 4 6 3 5 23 3 27 0 56 soboleva_modified_hyperbolic_tangent vector 0 2 0 4 0 6 0 8 array 0 11075085 0 28236685 0 07861169 0 1180085 0 22999056 0 1566043 separate the numerator and denominator for simplicity calculate the numerator and denominator element wise calculate and return the final result element wise
import numpy as np def soboleva_modified_hyperbolic_tangent( vector: np.ndarray, a_value: float, b_value: float, c_value: float, d_value: float ) -> np.ndarray: numerator = np.exp(a_value * vector) - np.exp(-b_value * vector) denominator = np.exp(c_value * vector) + np.exp(-d_value * vector) return numerator / denominator if __name__ == "__main__": import doctest doctest.testmod()
softplus activation function use case the softplus function is a smooth approximation of the relu function for more detailed information you can refer to the following link https en wikipedia orgwikirectifierneuralnetworkssoftplus implements the softplus activation function parameters vector np ndarray the input array for the softplus activation returns np ndarray the input array after applying the softplus activation formula fx ln1 ex examples softplusnp array2 3 0 6 2 3 8 array2 39554546 1 03748795 0 12692801 0 02212422 softplusnp array9 2 0 3 0 45 4 56 array1 01034298e04 5 54355244e01 9 43248946e01 1 04077103e02 implements the softplus activation function parameters vector np ndarray the input array for the softplus activation returns np ndarray the input array after applying the softplus activation formula f x ln 1 e x examples softplus np array 2 3 0 6 2 3 8 array 2 39554546 1 03748795 0 12692801 0 02212422 softplus np array 9 2 0 3 0 45 4 56 array 1 01034298e 04 5 54355244e 01 9 43248946e 01 1 04077103e 02
import numpy as np def softplus(vector: np.ndarray) -> np.ndarray: return np.log(1 + np.exp(vector)) if __name__ == "__main__": import doctest doctest.testmod()
squareplus activation function use case squareplus designed to enhance positive values and suppress negative values for more detailed information you can refer to the following link https en wikipedia orgwikirectifierneuralnetworkssquareplus implements the squareplus activation function parameters vector np ndarray the input array for the squareplus activation beta float size of the curved region returns np ndarray the input array after applying the squareplus activation formula fx x sqrtx2 b 2 examples squareplusnp array2 3 0 6 2 3 8 beta2 array2 5 1 06811457 0 22474487 0 12731349 squareplusnp array9 2 0 3 0 45 4 56 beta3 array0 0808119 0 72891979 1 11977651 0 15893419 implements the squareplus activation function parameters vector np ndarray the input array for the squareplus activation beta float size of the curved region returns np ndarray the input array after applying the squareplus activation formula f x x sqrt x 2 b 2 examples squareplus np array 2 3 0 6 2 3 8 beta 2 array 2 5 1 06811457 0 22474487 0 12731349 squareplus np array 9 2 0 3 0 45 4 56 beta 3 array 0 0808119 0 72891979 1 11977651 0 15893419
import numpy as np def squareplus(vector: np.ndarray, beta: float) -> np.ndarray: return (vector + np.sqrt(vector**2 + beta)) / 2 if __name__ == "__main__": import doctest doctest.testmod()
this script demonstrates the implementation of the sigmoid linear unit silu or swish function https en wikipedia orgwikirectifierneuralnetworks https en wikipedia orgwikiswishfunction the function takes a vector x of k real numbers as input and returns x sigmoidx swish is a smooth nonmonotonic function defined as fx x sigmoidx extensive experiments shows that swish consistently matches or outperforms relu on deep networks applied to a variety of challenging domains such as image classification and machine translation this script is inspired by a corresponding research paper https arxiv orgabs1710 05941 https blog paperspace comswishactivationfunction mathematical function sigmoid takes a vector x of k real numbers as input and returns 1 1 ex https en wikipedia orgwikisigmoidfunction sigmoidnp array1 0 1 0 2 0 array0 26894142 0 73105858 0 88079708 implements the sigmoid linear unit silu or swish function parameters vector np ndarray a numpy array consisting of real values returns swishvec np ndarray the input numpy array after applying swish examples sigmoidlinearunitnp array1 0 1 0 2 0 array0 26894142 0 73105858 1 76159416 sigmoidlinearunitnp array2 array0 23840584 parameters vector np ndarray a numpy array consisting of real values trainableparameter use to implement various swish activation functions returns swishvec np ndarray the input numpy array after applying swish examples swishnp array1 0 1 0 2 0 2 array0 11920292 0 88079708 1 96402758 swishnp array2 1 array0 23840584 mathematical function sigmoid takes a vector x of k real numbers as input and returns 1 1 e x https en wikipedia org wiki sigmoid_function sigmoid np array 1 0 1 0 2 0 array 0 26894142 0 73105858 0 88079708 implements the sigmoid linear unit silu or swish function parameters vector np ndarray a numpy array consisting of real values returns swish_vec np ndarray the input numpy array after applying swish examples sigmoid_linear_unit np array 1 0 1 0 2 0 array 0 26894142 0 73105858 1 76159416 sigmoid_linear_unit np array 2 array 0 23840584 parameters vector np ndarray a numpy array consisting of real values trainable_parameter use to implement various swish activation functions returns swish_vec np ndarray the input numpy array after applying swish examples swish np array 1 0 1 0 2 0 2 array 0 11920292 0 88079708 1 96402758 swish np array 2 1 array 0 23840584
import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-vector)) def sigmoid_linear_unit(vector: np.ndarray) -> np.ndarray: return vector * sigmoid(vector) def swish(vector: np.ndarray, trainable_parameter: int) -> np.ndarray: return vector * sigmoid(trainable_parameter * vector) if __name__ == "__main__": import doctest doctest.testmod()
usrbinpython a framework of back propagation neural networkbp model easy to use add many layers as you want clearly see how the loss decreasing easy to expand more activation functions more loss functions more optimization method stephen lee github https github comriptidebo date 2017 11 23 layers of bp neural network common connected layer of bp network param units numbers of neural units param activation activation function param learningrate learning rate for paras param isinputlayer whether it is input layer or not activation function may be sigmoid or linear input layer upgrade the negative gradient direction updates the weights and bias according to learning rate 0 3 if undefined back propagation neural network model forward propagation back propagation the inputlayer does not upgrade vector shape is the same as ydata shape usr bin python a framework of back propagation neural network bp model easy to use add many layers as you want clearly see how the loss decreasing easy to expand more activation functions more loss functions more optimization method stephen lee github https github com riptidebo date 2017 11 23 layers of bp neural network common connected layer of bp network param units numbers of neural units param activation activation function param learning_rate learning rate for paras param is_input_layer whether it is input layer or not activation function may be sigmoid or linear input layer i i 维 upgrade the negative gradient direction updates the weights and bias according to learning rate 0 3 if undefined back propagation neural network model forward propagation back propagation the input_layer does not upgrade vector shape is the same as _ydata shape
import numpy as np from matplotlib import pyplot as plt def sigmoid(x: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-x)) class DenseLayer: def __init__( self, units, activation=None, learning_rate=None, is_input_layer=False ): self.units = units self.weight = None self.bias = None self.activation = activation if learning_rate is None: learning_rate = 0.3 self.learn_rate = learning_rate self.is_input_layer = is_input_layer def initializer(self, back_units): self.weight = np.asmatrix(np.random.normal(0, 0.5, (self.units, back_units))) self.bias = np.asmatrix(np.random.normal(0, 0.5, self.units)).T if self.activation is None: self.activation = sigmoid def cal_gradient(self): if self.activation == sigmoid: gradient_mat = np.dot(self.output, (1 - self.output).T) gradient_activation = np.diag(np.diag(gradient_mat)) else: gradient_activation = 1 return gradient_activation def forward_propagation(self, xdata): self.xdata = xdata if self.is_input_layer: self.wx_plus_b = xdata self.output = xdata return xdata else: self.wx_plus_b = np.dot(self.weight, self.xdata) - self.bias self.output = self.activation(self.wx_plus_b) return self.output def back_propagation(self, gradient): gradient_activation = self.cal_gradient() gradient = np.asmatrix(np.dot(gradient.T, gradient_activation)) self._gradient_weight = np.asmatrix(self.xdata) self._gradient_bias = -1 self._gradient_x = self.weight self.gradient_weight = np.dot(gradient.T, self._gradient_weight.T) self.gradient_bias = gradient * self._gradient_bias self.gradient = np.dot(gradient, self._gradient_x).T self.weight = self.weight - self.learn_rate * self.gradient_weight self.bias = self.bias - self.learn_rate * self.gradient_bias.T return self.gradient class BPNN: def __init__(self): self.layers = [] self.train_mse = [] self.fig_loss = plt.figure() self.ax_loss = self.fig_loss.add_subplot(1, 1, 1) def add_layer(self, layer): self.layers.append(layer) def build(self): for i, layer in enumerate(self.layers[:]): if i < 1: layer.is_input_layer = True else: layer.initializer(self.layers[i - 1].units) def summary(self): for i, layer in enumerate(self.layers[:]): print(f"------- layer {i} -------") print("weight.shape ", np.shape(layer.weight)) print("bias.shape ", np.shape(layer.bias)) def train(self, xdata, ydata, train_round, accuracy): self.train_round = train_round self.accuracy = accuracy self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1) x_shape = np.shape(xdata) for _ in range(train_round): all_loss = 0 for row in range(x_shape[0]): _xdata = np.asmatrix(xdata[row, :]).T _ydata = np.asmatrix(ydata[row, :]).T for layer in self.layers: _xdata = layer.forward_propagation(_xdata) loss, gradient = self.cal_loss(_ydata, _xdata) all_loss = all_loss + loss for layer in self.layers[:0:-1]: gradient = layer.back_propagation(gradient) mse = all_loss / x_shape[0] self.train_mse.append(mse) self.plot_loss() if mse < self.accuracy: print("----达到精度----") return mse return None def cal_loss(self, ydata, ydata_): self.loss = np.sum(np.power((ydata - ydata_), 2)) self.loss_gradient = 2 * (ydata_ - ydata) return self.loss, self.loss_gradient def plot_loss(self): if self.ax_loss.lines: self.ax_loss.lines.remove(self.ax_loss.lines[0]) self.ax_loss.plot(self.train_mse, "r-") plt.ion() plt.xlabel("step") plt.ylabel("loss") plt.show() plt.pause(0.1) def example(): x = np.random.randn(10, 10) y = np.asarray( [ [0.8, 0.4], [0.4, 0.3], [0.34, 0.45], [0.67, 0.32], [0.88, 0.67], [0.78, 0.77], [0.55, 0.66], [0.55, 0.43], [0.54, 0.1], [0.1, 0.5], ] ) model = BPNN() for i in (10, 20, 30, 2): model.add_layer(DenseLayer(i)) model.build() model.summary() model.train(xdata=x, ydata=y, train_round=100, accuracy=0.01) if __name__ == "__main__": example()
forward propagation explanation https towardsdatascience comforwardpropagationinneuralnetworkssimplifiedmathandcodeversionbbcfef6f9250 sigmoid return the sigmoid function of a float sigmoidfunction3 5 0 9706877692486436 sigmoidfunction3 5 true 8 75 initial value return the value found after the forward propagation training res forwardpropagation32 450000 was 10000000 res 31 and res 33 true res forwardpropagation32 1000 res 31 and res 33 false random weight forward propagation how much did we miss error delta update weight sigmoid return the sigmoid function of a float sigmoid_function 3 5 0 9706877692486436 sigmoid_function 3 5 true 8 75 initial value return the value found after the forward propagation training res forward_propagation 32 450_000 was 10_000_000 res 31 and res 33 true res forward_propagation 32 1000 res 31 and res 33 false random weight forward propagation how much did we miss error delta update weight
import math import random def sigmoid_function(value: float, deriv: bool = False) -> float: if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value)) INITIAL_VALUE = 0.02 def forward_propagation(expected: int, number_propagations: int) -> float: weight = float(2 * (random.randint(1, 100)) - 1) for _ in range(number_propagations): layer_1 = sigmoid_function(INITIAL_VALUE * weight) layer_1_error = (expected / 100) - layer_1 layer_1_delta = layer_1_error * sigmoid_function(layer_1, True) weight += INITIAL_VALUE * layer_1_delta return layer_1 * 100 if __name__ == "__main__": import doctest doctest.testmod() expected = int(input("Expected value: ")) number_propagations = int(input("Number of propagations: ")) print(forward_propagation(expected, number_propagations))
the following implementation assumes that the activities are already sorted according to their finish time n total number of activities start an array that contains start time of all activities finish an array that contains finish time of all activities start 1 3 0 5 8 5 finish 2 4 6 7 9 9 printmaxactivitiesstart finish the following activities are selected 0 1 3 4 the first activity is always selected consider rest of the activities if this activity has start time greater than or equal to the finish time of previously selected activity then select it prints a maximum set of activities that can be done by a single person one at a time n total number of activities start an array that contains start time of all activities finish an array that contains finish time of all activities start 1 3 0 5 8 5 finish 2 4 6 7 9 9 print_max_activities start finish the following activities are selected 0 1 3 4 the first activity is always selected consider rest of the activities if this activity has start time greater than or equal to the finish time of previously selected activity then select it
def print_max_activities(start: list[int], finish: list[int]) -> None: n = len(finish) print("The following activities are selected:") i = 0 print(i, end=",") for j in range(n): if start[j] >= finish[i]: print(j, end=",") i = j if __name__ == "__main__": import doctest doctest.testmod() start = [1, 3, 0, 5, 8, 5] finish = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
the method arranges two lists as one list in alternative forms of the list elements param firstinputlist param secondinputlist return list alternativelistarrange1 2 3 4 5 a b c 1 a 2 b 3 c 4 5 alternativelistarrangea b c 1 2 3 4 5 a 1 b 2 c 3 4 5 alternativelistarrangex y z 9 8 7 6 x 9 y 8 z 7 6 alternativelistarrange1 2 3 4 5 1 2 3 4 5 the method arranges two lists as one list in alternative forms of the list elements param first_input_list param second_input_list return list alternative_list_arrange 1 2 3 4 5 a b c 1 a 2 b 3 c 4 5 alternative_list_arrange a b c 1 2 3 4 5 a 1 b 2 c 3 4 5 alternative_list_arrange x y z 9 8 7 6 x 9 y 8 z 7 6 alternative_list_arrange 1 2 3 4 5 1 2 3 4 5
def alternative_list_arrange(first_input_list: list, second_input_list: list) -> list: first_input_list_length: int = len(first_input_list) second_input_list_length: int = len(second_input_list) abs_length: int = ( first_input_list_length if first_input_list_length > second_input_list_length else second_input_list_length ) output_result_list: list = [] for char_count in range(abs_length): if char_count < first_input_list_length: output_result_list.append(first_input_list[char_count]) if char_count < second_input_list_length: output_result_list.append(second_input_list[char_count]) return output_result_list if __name__ == "__main__": print(alternative_list_arrange(["A", "B", "C"], [1, 2, 3, 4, 5]), end=" ")
a python implementation of the banker s algorithm in operating systems using processes and resources biney kingsley bluedistrogithub io bineykingsley36gmail com date 28102018 the banker s algorithm is a resource allocation and deadlock avoidance algorithm developed by edsger dijkstra that tests for safety by simulating the allocation of predetermined maximum possible amounts of all resources and then makes a sstate check to test for possible deadlock conditions for all other pending activities before deciding whether allocation should be allowed to continue source wikipedia credit rosetta code c implementation helped very much https rosettacode orgwikibanker27salgorithm param claimvector a nxnnxm list depicting the amount of each resources eg memory interface semaphores etc available param allocatedresourcestable a nxnnxm list depicting the amount of each resource each process is currently holding param maximumclaimtable a nxnnxm list depicting how much of each resource the system currently has available check for allocated resources in line with each resource in the claim vector check for available resources in line with each resource in the claim vector implement safety checker that calculates the needs by ensuring that maxclaimij alloctableij availj this function builds an index control dictionary to track original idsindices of processes when altered during execution of method main return 0 a int b int 1 c int d int bankersalgorithmtestclaimvector testallocatedrestable testmaximumclaimtable bankersalgorithmneedindexmanager doctest normalizewhitespace 0 1 2 0 3 1 0 1 3 1 2 1 1 0 2 3 1 3 2 0 4 2 0 0 3 utilize various methods in this class to simulate the banker s algorithm return none bankersalgorithmtestclaimvector testallocatedrestable testmaximumclaimtable maindescribetrue allocated resource table p1 2 0 1 1 blankline p2 0 1 2 1 blankline p3 4 0 0 3 blankline p4 0 2 1 0 blankline p5 1 0 3 0 blankline system resource table p1 3 2 1 4 blankline p2 0 2 5 2 blankline p3 5 1 0 5 blankline p4 1 5 3 0 blankline p5 3 0 3 3 blankline current usage by active processes 8 5 9 7 initial available resources 1 2 2 2 blankline process 3 is executing updated available resource stack for processes 5 2 2 5 the process is in a safe state blankline process 1 is executing updated available resource stack for processes 7 2 3 6 the process is in a safe state blankline process 2 is executing updated available resource stack for processes 7 3 5 7 the process is in a safe state blankline process 4 is executing updated available resource stack for processes 7 5 6 7 the process is in a safe state blankline process 5 is executing updated available resource stack for processes 8 5 9 7 the process is in a safe state blankline get the original index of the process from indctrl db remove the process run from stack update availablefreed resources stack properly align display of the algorithm s solution a python implementation of the banker s algorithm in operating systems using processes and resources biney kingsley bluedistro github io bineykingsley36 gmail com date 28 10 2018 the banker s algorithm is a resource allocation and deadlock avoidance algorithm developed by edsger dijkstra that tests for safety by simulating the allocation of predetermined maximum possible amounts of all resources and then makes a s state check to test for possible deadlock conditions for all other pending activities before deciding whether allocation should be allowed to continue source wikipedia credit rosetta code c implementation helped very much https rosettacode org wiki banker 27s_algorithm param claim_vector a nxn nxm list depicting the amount of each resources eg memory interface semaphores etc available param allocated_resources_table a nxn nxm list depicting the amount of each resource each process is currently holding param maximum_claim_table a nxn nxm list depicting how much of each resource the system currently has available check for allocated resources in line with each resource in the claim vector check for available resources in line with each resource in the claim vector implement safety checker that calculates the needs by ensuring that max_claim i j alloc_table i j avail j this function builds an index control dictionary to track original ids indices of processes when altered during execution of method main return 0 a int b int 1 c int d int bankersalgorithm test_claim_vector test_allocated_res_table test_maximum_claim_table _bankersalgorithm__need_index_manager doctest normalize_whitespace 0 1 2 0 3 1 0 1 3 1 2 1 1 0 2 3 1 3 2 0 4 2 0 0 3 utilize various methods in this class to simulate the banker s algorithm return none bankersalgorithm test_claim_vector test_allocated_res_table test_maximum_claim_table main describe true allocated resource table p1 2 0 1 1 blankline p2 0 1 2 1 blankline p3 4 0 0 3 blankline p4 0 2 1 0 blankline p5 1 0 3 0 blankline system resource table p1 3 2 1 4 blankline p2 0 2 5 2 blankline p3 5 1 0 5 blankline p4 1 5 3 0 blankline p5 3 0 3 3 blankline current usage by active processes 8 5 9 7 initial available resources 1 2 2 2 __________________________________________________ blankline process 3 is executing updated available resource stack for processes 5 2 2 5 the process is in a safe state blankline process 1 is executing updated available resource stack for processes 7 2 3 6 the process is in a safe state blankline process 2 is executing updated available resource stack for processes 7 3 5 7 the process is in a safe state blankline process 4 is executing updated available resource stack for processes 7 5 6 7 the process is in a safe state blankline process 5 is executing updated available resource stack for processes 8 5 9 7 the process is in a safe state blankline get the original index of the process from ind_ctrl db remove the process run from stack update available freed resources stack properly align display of the algorithm s solution
from __future__ import annotations import numpy as np test_claim_vector = [8, 5, 9, 7] test_allocated_res_table = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] test_maximum_claim_table = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class BankersAlgorithm: def __init__( self, claim_vector: list[int], allocated_resources_table: list[list[int]], maximum_claim_table: list[list[int]], ) -> None: self.__claim_vector = claim_vector self.__allocated_resources_table = allocated_resources_table self.__maximum_claim_table = maximum_claim_table def __processes_resource_summation(self) -> list[int]: return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def __available_resources(self) -> list[int]: return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation() ) def __need(self) -> list[list[int]]: return [ list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def __need_index_manager(self) -> dict[int, list[int]]: return {self.__need().index(i): i for i in self.__need()} def main(self, **kwargs) -> None: need_list = self.__need() alloc_resources_table = self.__allocated_resources_table available_resources = self.__available_resources() need_index_manager = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n") while need_list: safe = False for each_need in need_list: execution = True for index, need in enumerate(each_need): if need > available_resources[index]: execution = False break if execution: safe = True for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: process_number = original_need_index print(f"Process {process_number + 1} is executing.") need_list.remove(each_need) available_resources = np.array(available_resources) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(x) for x in available_resources]) ) break if safe: print("The process is in a safe state.\n") else: print("System in unsafe state. Aborting...\n") break def __pretty_data(self): print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( f"P{self.__allocated_resources_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print(" " * 9 + "System Resource Table") for item in self.__maximum_claim_table: print( f"P{self.__maximum_claim_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(x) for x in self.__claim_vector) ) print( "Initial Available Resources: " + " ".join(str(x) for x in self.__available_resources()) ) if __name__ == "__main__": import doctest doctest.testmod()
usrbinenv python3 davisputnamlogemannloveland dpll algorithm is a complete backtrackingbased search algorithm for deciding the satisfiability of propositional logic formulae in conjunctive normal form i e for solving the conjunctive normal form satisfiability cnfsat problem for more information about the algorithm https en wikipedia orgwikidpllalgorithm a clause represented in conjunctive normal form a clause is a set of literals either complemented or otherwise for example a1 a2 a3 is the clause a1 v a2 v a3 a5 a2 a1 is the clause a5 v a2 v a1 create model clause clausea1 a2 a3 clause evaluatea1 true true represent the literals and an assignment in a clause assign all literals to none initially to print a clause as in conjunctive normal form strclausea1 a2 a3 a1 a2 a3 to print a clause as in conjunctive normal form lenclause 0 lenclausea1 a2 a3 3 assign values to literals of the clause as given by model complement assignment if literal is in complemented form evaluates the clause with the assignments in model this has the following steps 1 return true if both a literal and its complement exist in the clause 2 return true if a single literal has the assignment true 3 return noneunable to complete evaluation if a literal has no assignment 4 compute disjunction of all values assigned in clause a formula represented in conjunctive normal form a formula is a set of clauses for example a1 a2 a3 a5 a2 a1 is a1 v a2 v a3 and a5 v a2 v a1 represent the number of clauses and the clauses themselves to print a formula as in conjunctive normal form strformulaclausea1 a2 a3 clausea5 a2 a1 a1 a2 a3 a5 a2 a1 randomly generate a clause all literals have the name ax where x is an integer from 1 to 5 randomly generate a formula return the clauses and symbols from a formula a symbol is the uncomplemented form of a literal for example symbol of a3 is a3 symbol of a5 is a5 formula formulaclausea1 a2 a3 clausea5 a2 a1 clauses symbols generateparametersformula clauseslist stri for i in clauses clauseslist a1 a2 a3 a5 a2 a1 symbols a1 a2 a3 a5 return pure symbols and their values to satisfy clause pure symbols are symbols in a formula that exist only in one form either complemented or otherwise for example a4 a3 a5 a1 a3 a4 a3 has pure symbols a4 a5 and a1 this has the following steps 1 ignore clauses that have already evaluated to be true 2 find symbols that occur only in one form in the rest of the clauses 3 assign value true or false depending on whether the symbols occurs in normal or complemented form respectively formula formulaclausea1 a2 a3 clausea5 a2 a1 clauses symbols generateparametersformula puresymbols values findpuresymbolsclauses symbols puresymbols a1 a2 a3 a5 values a1 true a2 false a3 true a5 false returns the unit symbols and their values to satisfy clause unit symbols are symbols in a formula that are either the only symbol in a clause or all other literals in that clause have been assigned false this has the following steps 1 find symbols that are the only occurrences in a clause 2 find symbols in a clause where all other literals are assigned false 3 assign true or false depending on whether the symbols occurs in normal or complemented form respectively clause1 clausea4 a3 a5 a1 a3 clause2 clausea4 clause3 clausea3 clauses symbols generateparametersformulaclause1 clause2 clause3 unitclauses values findunitclausesclauses unitclauses a4 a3 values a4 true a3 true returns the model if the formula is satisfiable else none this has the following steps 1 if every clause in clauses is true return true 2 if some clause in clauses is false return false 3 find pure symbols 4 find unit symbols formula formulaclausea4 a3 a5 a1 a3 clausea4 clauses symbols generateparametersformula soln model dpllalgorithmclauses symbols soln true model a4 true usr bin env python3 davis putnam logemann loveland dpll algorithm is a complete backtracking based search algorithm for deciding the satisfiability of propositional logic formulae in conjunctive normal form i e for solving the conjunctive normal form satisfiability cnf sat problem for more information about the algorithm https en wikipedia org wiki dpll_algorithm a clause represented in conjunctive normal form a clause is a set of literals either complemented or otherwise for example a1 a2 a3 is the clause a1 v a2 v a3 a5 a2 a1 is the clause a5 v a2 v a1 create model clause clause a1 a2 a3 clause evaluate a1 true true represent the literals and an assignment in a clause assign all literals to none initially to print a clause as in conjunctive normal form str clause a1 a2 a3 a1 a2 a3 to print a clause as in conjunctive normal form len clause 0 len clause a1 a2 a3 3 assign values to literals of the clause as given by model complement assignment if literal is in complemented form evaluates the clause with the assignments in model this has the following steps 1 return true if both a literal and its complement exist in the clause 2 return true if a single literal has the assignment true 3 return none unable to complete evaluation if a literal has no assignment 4 compute disjunction of all values assigned in clause a formula represented in conjunctive normal form a formula is a set of clauses for example a1 a2 a3 a5 a2 a1 is a1 v a2 v a3 and a5 v a2 v a1 represent the number of clauses and the clauses themselves to print a formula as in conjunctive normal form str formula clause a1 a2 a3 clause a5 a2 a1 a1 a2 a3 a5 a2 a1 randomly generate a clause all literals have the name ax where x is an integer from 1 to 5 randomly generate a formula return the clauses and symbols from a formula a symbol is the uncomplemented form of a literal for example symbol of a3 is a3 symbol of a5 is a5 formula formula clause a1 a2 a3 clause a5 a2 a1 clauses symbols generate_parameters formula clauses_list str i for i in clauses clauses_list a1 a2 a3 a5 a2 a1 symbols a1 a2 a3 a5 return pure symbols and their values to satisfy clause pure symbols are symbols in a formula that exist only in one form either complemented or otherwise for example a4 a3 a5 a1 a3 a4 a3 has pure symbols a4 a5 and a1 this has the following steps 1 ignore clauses that have already evaluated to be true 2 find symbols that occur only in one form in the rest of the clauses 3 assign value true or false depending on whether the symbols occurs in normal or complemented form respectively formula formula clause a1 a2 a3 clause a5 a2 a1 clauses symbols generate_parameters formula pure_symbols values find_pure_symbols clauses symbols pure_symbols a1 a2 a3 a5 values a1 true a2 false a3 true a5 false returns the unit symbols and their values to satisfy clause unit symbols are symbols in a formula that are either the only symbol in a clause or all other literals in that clause have been assigned false this has the following steps 1 find symbols that are the only occurrences in a clause 2 find symbols in a clause where all other literals are assigned false 3 assign true or false depending on whether the symbols occurs in normal or complemented form respectively clause1 clause a4 a3 a5 a1 a3 clause2 clause a4 clause3 clause a3 clauses symbols generate_parameters formula clause1 clause2 clause3 unit_clauses values find_unit_clauses clauses unit_clauses a4 a3 values a4 true a3 true returns the model if the formula is satisfiable else none this has the following steps 1 if every clause in clauses is true return true 2 if some clause in clauses is false return false 3 find pure symbols 4 find unit symbols formula formula clause a4 a3 a5 a1 a3 clause a4 clauses symbols generate_parameters formula soln model dpll_algorithm clauses symbols soln true model a4 true
from __future__ import annotations import random from collections.abc import Iterable class Clause: def __init__(self, literals: list[str]) -> None: self.literals: dict[str, bool | None] = {literal: None for literal in literals} def __str__(self) -> str: return "{" + " , ".join(self.literals) + "}" def __len__(self) -> int: return len(self.literals) def assign(self, model: dict[str, bool | None]) -> None: for literal in self.literals: symbol = literal[:2] if symbol in model: value = model[symbol] else: continue if value is not None: if literal.endswith("'"): value = not value self.literals[literal] = value def evaluate(self, model: dict[str, bool | None]) -> bool | None: for literal in self.literals: symbol = literal.rstrip("'") if literal.endswith("'") else literal + "'" if symbol in self.literals: return True self.assign(model) for value in self.literals.values(): if value in (True, None): return value return any(self.literals.values()) class Formula: def __init__(self, clauses: Iterable[Clause]) -> None: self.clauses = list(clauses) def __str__(self) -> str: return "{" + " , ".join(str(clause) for clause in self.clauses) + "}" def generate_clause() -> Clause: literals = [] no_of_literals = random.randint(1, 5) base_var = "A" i = 0 while i < no_of_literals: var_no = random.randint(1, 5) var_name = base_var + str(var_no) var_complement = random.randint(0, 1) if var_complement == 1: var_name += "'" if var_name in literals: i -= 1 else: literals.append(var_name) i += 1 return Clause(literals) def generate_formula() -> Formula: clauses: set[Clause] = set() no_of_clauses = random.randint(1, 10) while len(clauses) < no_of_clauses: clauses.add(generate_clause()) return Formula(clauses) def generate_parameters(formula: Formula) -> tuple[list[Clause], list[str]]: clauses = formula.clauses symbols_set = [] for clause in formula.clauses: for literal in clause.literals: symbol = literal[:2] if symbol not in symbols_set: symbols_set.append(symbol) return clauses, symbols_set def find_pure_symbols( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[list[str], dict[str, bool | None]]: pure_symbols = [] assignment: dict[str, bool | None] = {} literals = [] for clause in clauses: if clause.evaluate(model): continue for literal in clause.literals: literals.append(literal) for s in symbols: sym = s + "'" if (s in literals and sym not in literals) or ( s not in literals and sym in literals ): pure_symbols.append(s) for p in pure_symbols: assignment[p] = None for s in pure_symbols: sym = s + "'" if s in literals: assignment[s] = True elif sym in literals: assignment[s] = False return pure_symbols, assignment def find_unit_clauses( clauses: list[Clause], model: dict[str, bool | None] ) -> tuple[list[str], dict[str, bool | None]]: unit_symbols = [] for clause in clauses: if len(clause) == 1: unit_symbols.append(next(iter(clause.literals.keys()))) else: f_count, n_count = 0, 0 for literal, value in clause.literals.items(): if value is False: f_count += 1 elif value is None: sym = literal n_count += 1 if f_count == len(clause) - 1 and n_count == 1: unit_symbols.append(sym) assignment: dict[str, bool | None] = {} for i in unit_symbols: symbol = i[:2] assignment[symbol] = len(i) == 2 unit_symbols = [i[:2] for i in unit_symbols] return unit_symbols, assignment def dpll_algorithm( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[bool | None, dict[str, bool | None] | None]: check_clause_all_true = True for clause in clauses: clause_check = clause.evaluate(model) if clause_check is False: return False, None elif clause_check is None: check_clause_all_true = False continue if check_clause_all_true: return True, model try: pure_symbols, assignment = find_pure_symbols(clauses, symbols, model) except RecursionError: print("raises a RecursionError and is") return None, {} p = None if len(pure_symbols) > 0: p, value = pure_symbols[0], assignment[pure_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) unit_symbols, assignment = find_unit_clauses(clauses, model) p = None if len(unit_symbols) > 0: p, value = unit_symbols[0], assignment[unit_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) p = symbols[0] rest = symbols[1:] tmp1, tmp2 = model, model tmp1[p], tmp2[p] = True, False return dpll_algorithm(clauses, rest, tmp1) or dpll_algorithm(clauses, rest, tmp2) if __name__ == "__main__": import doctest doctest.testmod() formula = generate_formula() print(f"The formula {formula} is", end=" ") clauses, symbols = generate_parameters(formula) solution, model = dpll_algorithm(clauses, symbols, {}) if solution: print(f"satisfiable with the assignment {model}.") else: print("not satisfiable.")
binpython3 doomsday algorithm info https en wikipedia orgwikidoomsdayrule returns the weekday name out of a given date getweekday2020 10 24 saturday getweekday2017 10 24 tuesday getweekday2019 5 3 friday getweekday1970 9 16 wednesday getweekday1870 8 13 saturday getweekday2040 3 14 wednesday minimal input check doomsday algorithm bin python3 doomsday algorithm info https en wikipedia org wiki doomsday_rule returns the week day name out of a given date get_week_day 2020 10 24 saturday get_week_day 2017 10 24 tuesday get_week_day 2019 5 3 friday get_week_day 1970 9 16 wednesday get_week_day 1870 8 13 saturday get_week_day 2040 3 14 wednesday minimal input check doomsday algorithm
DOOMSDAY_LEAP = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] DOOMSDAY_NOT_LEAP = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] WEEK_DAY_NAMES = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def get_week_day(year: int, month: int, day: int) -> str: assert len(str(year)) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" century = year // 100 century_anchor = (5 * (century % 4) + 2) % 7 centurian = year % 100 centurian_m = centurian % 12 dooms_day = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 day_anchor = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) week_day = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
usrbinpython the fisheryates shuffle is an algorithm for generating a random permutation of a finite sequence for more details visit wikipediafischeryatesshuffle usr bin python the fisher yates shuffle is an algorithm for generating a random permutation of a finite sequence for more details visit wikipedia fischer yates shuffle
import random from typing import Any def fisher_yates_shuffle(data: list) -> list[Any]: for _ in range(len(data)): a = random.randint(0, len(data) - 1) b = random.randint(0, len(data) - 1) data[a], data[b] = data[b], data[a] return data if __name__ == "__main__": integers = [0, 1, 2, 3, 4, 5, 6, 7] strings = ["python", "says", "hello", "!"] print("Fisher-Yates Shuffle:") print("List", integers, strings) print("FY Shuffle", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
https en wikipedia orgwikicomputusgauss easteralgorithm calculation gregorian easter date for given year gausseaster2007 datetime datetime2007 4 8 0 0 gausseaster2008 datetime datetime2008 3 23 0 0 gausseaster2020 datetime datetime2020 4 12 0 0 gausseaster2021 datetime datetime2021 4 4 0 0 days to be added to march 21 phm paschal full moon calculation gregorian easter date for given year gauss_easter 2007 datetime datetime 2007 4 8 0 0 gauss_easter 2008 datetime datetime 2008 3 23 0 0 gauss_easter 2020 datetime datetime 2020 4 12 0 0 gauss_easter 2021 datetime datetime 2021 4 4 0 0 days to be added to march 21 phm paschal full moon
import math from datetime import datetime, timedelta def gauss_easter(year: int) -> datetime: metonic_cycle = year % 19 julian_leap_year = year % 4 non_leap_year = year % 7 leap_day_inhibits = math.floor(year / 100) lunar_orbit_correction = math.floor((13 + 8 * leap_day_inhibits) / 25) leap_day_reinstall_number = leap_day_inhibits / 4 secular_moon_shift = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 century_starting_point = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 days_to_add = (19 * metonic_cycle + secular_moon_shift) % 30 days_from_phm_to_sunday = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(year, 4, 19) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(year, 4, 18) else: return datetime(year, 3, 22) + timedelta( days=int(days_to_add + days_from_phm_to_sunday) ) if __name__ == "__main__": for year in (1994, 2000, 2010, 2021, 2023): tense = "will be" if year > datetime.now().year else "was" print(f"Easter in {year} {tense} {gauss_easter(year)}")
this is a pure python implementation of the graham scan algorithm source https en wikipedia orgwikigrahamscan for doctests run following command python3 m doctest v grahamscan py traversal from the lowest and the most left point in anticlockwise direction if direction gets right the previous point is not the convex hull return the angle toward to point from minx miny param point the target point minx the starting point s x miny the starting point s y return the angle examples anglecomparer1 1 0 0 45 0 anglecomparer100 1 10 10 5 710593137499642 anglecomparer5 5 2 3 33 690067525979785 sort the points accorgind to the angle from the lowest and the most left point return the direction toward to the line from via to target from starting param starting the starting point via the via point target the target point return the direction examples checkdirection1 1 2 2 3 3 direction straight checkdirection60 1 50 199 30 2 direction left checkdirection0 0 5 5 10 0 direction right t v s viaangle is always lower than targetangle if direction is left if they are same it means they are on a same line of convex hull pure implementation of graham scan algorithm in python param points the unique points on coordinates return the points on convex hell examples grahamscan9 6 3 1 0 0 5 5 5 2 7 0 3 3 1 4 0 0 7 0 9 6 5 5 1 4 grahamscan0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 grahamscan0 0 1 1 2 2 3 3 1 2 0 0 1 1 2 2 3 3 1 2 grahamscan100 20 99 3 1 10000001 5133186 25 66 4 5133186 25 1 10000001 100 20 66 4 there is no convex hull find the lowest and the most left point remove the lowest and the most left point from points for preparing for sort this insert actually costs complexity and you should instead add minx miny into stack later i m using insert just for easy understanding the first 3 points lines are towards the left because we sort them by their angle from minx miny we keep currentdirection as left because if the straight line keeps as straight we want to know if this straight line is towards left if the straight line is towards right every previous points on that straight line is not convex hull traversal from the lowest and the most left point in anti clockwise direction if direction gets right the previous point is not the convex hull return the angle toward to point from minx miny param point the target point minx the starting point s x miny the starting point s y return the angle examples angle_comparer 1 1 0 0 45 0 angle_comparer 100 1 10 10 5 710593137499642 angle_comparer 5 5 2 3 33 690067525979785 sort the points accorgind to the angle from the lowest and the most left point return the direction toward to the line from via to target from starting param starting the starting point via the via point target the target point return the direction examples check_direction 1 1 2 2 3 3 direction straight check_direction 60 1 50 199 30 2 direction left check_direction 0 0 5 5 10 0 direction right t v s via_angle is always lower than target_angle if direction is left if they are same it means they are on a same line of convex hull pure implementation of graham scan algorithm in python param points the unique points on coordinates return the points on convex hell examples graham_scan 9 6 3 1 0 0 5 5 5 2 7 0 3 3 1 4 0 0 7 0 9 6 5 5 1 4 graham_scan 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 graham_scan 0 0 1 1 2 2 3 3 1 2 0 0 1 1 2 2 3 3 1 2 graham_scan 100 20 99 3 1 10000001 5133186 25 66 4 5133186 25 1 10000001 100 20 66 4 there is no convex hull find the lowest and the most left point remove the lowest and the most left point from points for preparing for sort this insert actually costs complexity and you should instead add minx miny into stack later i m using insert just for easy understanding the first 3 points lines are towards the left because we sort them by their angle from minx miny we keep current_direction as left because if the straight line keeps as straight we want to know if this straight line is towards left if the straight line is towards right every previous points on that straight line is not convex hull
from __future__ import annotations from collections import deque from enum import Enum from math import atan2, degrees from sys import maxsize class Direction(Enum): left = 1 straight = 2 right = 3 def __repr__(self): return f"{self.__class__.__name__}.{self.name}" def angle_comparer(point: tuple[int, int], minx: int, miny: int) -> float: x, y = point return degrees(atan2(y - miny, x - minx)) def check_direction( starting: tuple[int, int], via: tuple[int, int], target: tuple[int, int] ) -> Direction: x0, y0 = starting x1, y1 = via x2, y2 = target via_angle = degrees(atan2(y1 - y0, x1 - x0)) via_angle %= 360 target_angle = degrees(atan2(y2 - y0, x2 - x0)) target_angle %= 360 if target_angle > via_angle: return Direction.left elif target_angle == via_angle: return Direction.straight else: return Direction.right def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]: if len(points) <= 2: raise ValueError("graham_scan: argument must contain more than 3 points.") if len(points) == 3: return points minidx = 0 miny, minx = maxsize, maxsize for i, point in enumerate(points): x = point[0] y = point[1] if y < miny: miny = y minx = x minidx = i if y == miny and x < minx: minx = x minidx = i points.pop(minidx) sorted_points = sorted(points, key=lambda point: angle_comparer(point, minx, miny)) sorted_points.insert(0, (minx, miny)) stack: deque[tuple[int, int]] = deque() stack.append(sorted_points[0]) stack.append(sorted_points[1]) stack.append(sorted_points[2]) current_direction = Direction.left for i in range(3, len(sorted_points)): while True: starting = stack[-2] via = stack[-1] target = sorted_points[i] next_direction = check_direction(starting, via, target) if next_direction == Direction.left: current_direction = Direction.left break if next_direction == Direction.straight: if current_direction == Direction.left: break elif current_direction == Direction.right: stack.pop() if next_direction == Direction.right: stack.pop() stack.append(sorted_points[i]) return list(stack)
guess the number using lower higher and the value to find or guess solution works by dividing lower and higher of number guessed suppose lower is 0 higher is 1000 and the number to guess is 355 guessthenumber10 1000 17 started guess the number 17 details 505 257 133 71 40 25 17 temporary input values for tests tempinputvalueoptiontrue 10 tempinputvalueoptionfalse 1000 tempinputvalueminval100 optiontrue 100 tempinputvalueminval100 maxval50 traceback most recent call last valueerror invalid value for minval or maxval minvalue maxvalue tempinputvalueten fifty 1 traceback most recent call last assertionerror invalid type of values specified to function tempinputvalueminval100 maxval500 100 tempinputvalueminval5100 maxval100 5100 return the midnumberwhole of two integers a and b getavg10 15 12 getavg20 300 160 getavgabcd 300 traceback most recent call last typeerror can only concatenate str not int to str getavg10 5 50 25 30 the guessthenumber function that guess the number by some operations and using inner functions guessthenumber10 1000 17 started guess the number 17 details 505 257 133 71 40 25 17 guessthenumber10000 10000 7 started guess the number 7 details 0 5000 2500 1250 625 312 156 78 39 19 9 4 6 7 guessthenumber10 1000 a traceback most recent call last assertionerror argument values must be type of int guessthenumber10 1000 5 traceback most recent call last valueerror guess value must be within the range of lower and higher value guessthenumber10000 100 5 traceback most recent call last valueerror argument value for lower and higher must belower higher returns value by comparing with entered toguess number starting point or function of script temporary input values for tests temp_input_value option true 10 temp_input_value option false 1000 temp_input_value min_val 100 option true 100 temp_input_value min_val 100 max_val 50 traceback most recent call last valueerror invalid value for min_val or max_val min_value max_value temp_input_value ten fifty 1 traceback most recent call last assertionerror invalid type of value s specified to function temp_input_value min_val 100 max_val 500 100 temp_input_value min_val 5100 max_val 100 5100 return the mid number whole of two integers a and b get_avg 10 15 12 get_avg 20 300 160 get_avg abcd 300 traceback most recent call last typeerror can only concatenate str not int to str get_avg 10 5 50 25 30 the guess_the_number function that guess the number by some operations and using inner functions guess_the_number 10 1000 17 started guess the number 17 details 505 257 133 71 40 25 17 guess_the_number 10000 10000 7 started guess the number 7 details 0 5000 2500 1250 625 312 156 78 39 19 9 4 6 7 guess_the_number 10 1000 a traceback most recent call last assertionerror argument values must be type of int guess_the_number 10 1000 5 traceback most recent call last valueerror guess value must be within the range of lower and higher value guess_the_number 10000 100 5 traceback most recent call last valueerror argument value for lower and higher must be lower higher returns value by comparing with entered to_guess number starting point or function of script
def temp_input_value( min_val: int = 10, max_val: int = 1000, option: bool = True ) -> int: assert ( isinstance(min_val, int) and isinstance(max_val, int) and isinstance(option, bool) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("Invalid value for min_val or max_val (min_value < max_value)") return min_val if option else max_val def get_avg(number_1: int, number_2: int) -> int: return int((number_1 + number_2) / 2) def guess_the_number(lower: int, higher: int, to_guess: int) -> None: assert ( isinstance(lower, int) and isinstance(higher, int) and isinstance(to_guess, int) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("argument value for lower and higher must be(lower > higher)") if not lower < to_guess < higher: raise ValueError( "guess value must be within the range of lower and higher value" ) def answer(number: int) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("started...") last_lowest = lower last_highest = higher last_numbers = [] while True: number = get_avg(last_lowest, last_highest) last_numbers.append(number) if answer(number) == "low": last_lowest = number elif answer(number) == "high": last_highest = number else: break print(f"guess the number : {last_numbers[-1]}") print(f"details : {last_numbers!s}") def main() -> None: lower = int(input("Enter lower value : ").strip()) higher = int(input("Enter high value : ").strip()) guess = int(input("Enter value to guess : ").strip()) guess_the_number(lower, higher, guess) if __name__ == "__main__": main()
task given an array of integers citations where citationsi is the number of citations a researcher received for their ith paper return compute the researcher s hindex according to the definition of hindex on wikipedia a scientist has an index h if h of their n papers have at least h citations each and the other n h papers have no more than h citations each if there are several possible values for h the maximum one is taken as the hindex hindex link https en wikipedia orgwikihindex implementation notes use sorting of array leetcode link https leetcode comproblemshindexdescription n lencitations runtime complexity on logn space complexity o1 return hindex of citations hindex3 0 6 1 5 3 hindex1 3 1 1 hindex1 2 3 2 hindex test traceback most recent call last valueerror the citations should be a list of non negative integers hindex1 2 3 traceback most recent call last valueerror the citations should be a list of non negative integers hindex1 2 3 traceback most recent call last valueerror the citations should be a list of non negative integers validate return h index of citations h_index 3 0 6 1 5 3 h_index 1 3 1 1 h_index 1 2 3 2 h_index test traceback most recent call last valueerror the citations should be a list of non negative integers h_index 1 2 3 traceback most recent call last valueerror the citations should be a list of non negative integers h_index 1 2 3 traceback most recent call last valueerror the citations should be a list of non negative integers validate
def h_index(citations: list[int]) -> int: if not isinstance(citations, list) or not all( isinstance(item, int) and item >= 0 for item in citations ): raise ValueError("The citations should be a list of non negative integers.") citations.sort() len_citations = len(citations) for i in range(len_citations): if citations[len_citations - 1 - i] <= i: return i return len_citations if __name__ == "__main__": import doctest doctest.testmod()
page replacement algorithm least recently used lru caching lrucache lrucachestr int lrucache4 lrucache refera lrucache refer2 lrucache refer3 lrucache lrucache4 3 2 a lrucache refera lrucache lrucache4 a 3 2 lrucache refer4 lrucache refer5 lrucache lrucache4 5 4 a 3 creates an empty store and map for the keys the lrucache is set the size n looks for a page in the cache store and adds reference to the set remove the least recently used key if the store is full update store to reflect recent access prints all the elements in the store page replacement algorithm least recently used lru caching lru_cache lrucache str int lrucache 4 lru_cache refer a lru_cache refer 2 lru_cache refer 3 lru_cache lrucache 4 3 2 a lru_cache refer a lru_cache lrucache 4 a 3 2 lru_cache refer 4 lru_cache refer 5 lru_cache lrucache 4 5 4 a 3 cache store of keys references of the keys in cache maximum capacity of cache creates an empty store and map for the keys the lrucache is set the size n looks for a page in the cache store and adds reference to the set remove the least recently used key if the store is full update store to reflect recent access prints all the elements in the store
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar T = TypeVar("T") class LRUCache(Generic[T]): dq_store: deque[T] key_reference: set[T] _MAX_CAPACITY: int = 10 def __init__(self, n: int) -> None: self.dq_store = deque() self.key_reference = set() if not n: LRUCache._MAX_CAPACITY = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0.") else: LRUCache._MAX_CAPACITY = n def refer(self, x: T) -> None: if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() self.key_reference.remove(last_element) else: self.dq_store.remove(x) self.dq_store.appendleft(x) self.key_reference.add(x) def display(self) -> None: for k in self.dq_store: print(k) def __repr__(self) -> str: return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}" if __name__ == "__main__": import doctest doctest.testmod() lru_cache: LRUCache[str | int] = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
double linked list node built specifically for lfu cache node doublelinkedlistnode1 1 node node key 1 val 1 freq 0 has next false has prev false double linked list built specifically for lfu cache dll doublelinkedlist doublelinkedlist dll doublelinkedlist node key none val none freq 0 has next true has prev false node key none val none freq 0 has next false has prev true firstnode doublelinkedlistnode1 10 firstnode node key 1 val 10 freq 0 has next false has prev false dll addfirstnode dll doublelinkedlist node key none val none freq 0 has next true has prev false node key 1 val 10 freq 1 has next true has prev true node key none val none freq 0 has next false has prev true node is mutated firstnode node key 1 val 10 freq 1 has next true has prev true secondnode doublelinkedlistnode2 20 secondnode node key 2 val 20 freq 0 has next false has prev false dll addsecondnode dll doublelinkedlist node key none val none freq 0 has next true has prev false node key 1 val 10 freq 1 has next true has prev true node key 2 val 20 freq 1 has next true has prev true node key none val none freq 0 has next false has prev true removednode dll removefirstnode assert removednode firstnode dll doublelinkedlist node key none val none freq 0 has next true has prev false node key 2 val 20 freq 1 has next true has prev true node key none val none freq 0 has next false has prev true attempt to remove node not on list removednode dll removefirstnode removednode is none true attempt to remove head or rear dll head node key none val none freq 0 has next true has prev false dll removedll head is none true attempt to remove head or rear dll rear node key none val none freq 0 has next false has prev true dll removedll rear is none true adds the given node at the tail of the list and shifting it to proper position all nodes other than self head are guaranteed to have nonnone previous moves node forward to maintain invariant of sort by freq value swap node with previous node removes and returns the given node from the list returns none if node prev or node next is none lfu cache to store a given capacity of data can be used as a standalone object or as a function decorator cache lfucache2 cache put1 1 cache put2 2 cache get1 1 cache put3 3 cache get2 is none true cache put4 4 cache get1 is none true cache get3 3 cache get4 4 cache cacheinfohits3 misses2 capacity2 currentsize2 lfucache decorator100 def fibnum if num in 1 2 return 1 return fibnum 1 fibnum 2 for i in range1 101 res fibi fib cacheinfo cacheinfohits196 misses100 capacity100 currentsize100 class variable to map the decorator functions to their respective instance return the details for the cache instance hits misses capacity currentsize cache lfucache1 1 in cache false cache put1 1 1 in cache true returns the value for the input key and updates the double linked list returns returns none if key is not present in cache node is guaranteed not none because it is in self cache sets the value for the input key and updates the double linked list delete first node when over capacity guaranteed to have a nonnone first node when numkeys 0 explain to type checker via assertions firstnode guaranteed to be in list decorator version of lfu cache decorated function must be function of t u double linked list node built specifically for lfu cache node doublelinkedlistnode 1 1 node node key 1 val 1 freq 0 has next false has prev false double linked list built specifically for lfu cache dll doublelinkedlist doublelinkedlist dll doublelinkedlist node key none val none freq 0 has next true has prev false node key none val none freq 0 has next false has prev true first_node doublelinkedlistnode 1 10 first_node node key 1 val 10 freq 0 has next false has prev false dll add first_node dll doublelinkedlist node key none val none freq 0 has next true has prev false node key 1 val 10 freq 1 has next true has prev true node key none val none freq 0 has next false has prev true node is mutated first_node node key 1 val 10 freq 1 has next true has prev true second_node doublelinkedlistnode 2 20 second_node node key 2 val 20 freq 0 has next false has prev false dll add second_node dll doublelinkedlist node key none val none freq 0 has next true has prev false node key 1 val 10 freq 1 has next true has prev true node key 2 val 20 freq 1 has next true has prev true node key none val none freq 0 has next false has prev true removed_node dll remove first_node assert removed_node first_node dll doublelinkedlist node key none val none freq 0 has next true has prev false node key 2 val 20 freq 1 has next true has prev true node key none val none freq 0 has next false has prev true attempt to remove node not on list removed_node dll remove first_node removed_node is none true attempt to remove head or rear dll head node key none val none freq 0 has next true has prev false dll remove dll head is none true attempt to remove head or rear dll rear node key none val none freq 0 has next false has prev true dll remove dll rear is none true adds the given node at the tail of the list and shifting it to proper position all nodes other than self head are guaranteed to have non none previous moves node forward to maintain invariant of sort by freq value swap node with previous node removes and returns the given node from the list returns none if node prev or node next is none lfu cache to store a given capacity of data can be used as a stand alone object or as a function decorator cache lfucache 2 cache put 1 1 cache put 2 2 cache get 1 1 cache put 3 3 cache get 2 is none true cache put 4 4 cache get 1 is none true cache get 3 3 cache get 4 4 cache cacheinfo hits 3 misses 2 capacity 2 current_size 2 lfucache decorator 100 def fib num if num in 1 2 return 1 return fib num 1 fib num 2 for i in range 1 101 res fib i fib cache_info cacheinfo hits 196 misses 100 capacity 100 current_size 100 class variable to map the decorator functions to their respective instance return the details for the cache instance hits misses capacity current_size cache lfucache 1 1 in cache false cache put 1 1 1 in cache true returns the value for the input key and updates the double linked list returns returns none if key is not present in cache node is guaranteed not none because it is in self cache sets the value for the input key and updates the double linked list delete first node when over capacity guaranteed to have a non none first node when num_keys 0 explain to type checker via assertions first_node guaranteed to be in list node guaranteed to be in list decorator version of lfu cache decorated function must be function of t u noqa b010
from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode(Generic[T, U]): def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.freq: int = 0 self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: return "Node: key: {}, val: {}, freq: {}, has next: {}, has prev: {}".format( self.key, self.val, self.freq, self.next is not None, self.prev is not None ) class DoubleLinkedList(Generic[T, U]): def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: previous = self.rear.prev assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear node.freq += 1 self._position_node(node) def _position_node(self, node: DoubleLinkedListNode[T, U]) -> None: while node.prev is not None and node.prev.freq > node.freq: previous_node = node.prev node.prev = previous_node.prev previous_node.next = node.prev node.next = previous_node previous_node.prev = node def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node class LFUCache(Generic[T, U]): decorator_function_to_instance_map: dict[Callable[[T], U], LFUCache[T, U]] = {} def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current_size={self.num_keys})" ) def __contains__(self, key: T) -> bool: return key in self.cache def get(self, key: T) -> U | None: if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node assert node is not None self.list.add(node) return node.val self.miss += 1 return None def put(self, key: T, value: U) -> None: if key not in self.cache: if self.num_keys >= self.capacity: first_node = self.list.head.next assert first_node is not None assert first_node.key is not None assert self.list.remove(first_node) is not None del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: node = self.list.remove(self.cache[key]) assert node is not None node.val = value self.list.add(node) @classmethod def decorator( cls: type[LFUCache[T, U]], size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: def cache_decorator_wrapper(*args: T) -> U: if func not in cls.decorator_function_to_instance_map: cls.decorator_function_to_instance_map[func] = LFUCache(size) result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) cls.decorator_function_to_instance_map[func].put(args[0], result) return result def cache_info() -> LFUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(cache_decorator_wrapper, "cache_info", cache_info) return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
a pseudorandom number generator the default value for seed is the result of a function call which is not normally recommended and causes ruff to raise a b008 error however in this case it is acceptable because linearcongruentialgenerator init will only be called once per instance and it ensures that each instance will generate a unique sequence of numbers these parameters are saved and used when nextnumber is called modulo is the largest number that can be generated exclusive the most efficient values are powers of 2 232 is a common value the smallest number that can be generated is zero the largest number that can be generated is modulo1 modulo is set in the constructor show the lcg in action a pseudorandom number generator the default value for seed is the result of a function call which is not normally recommended and causes ruff to raise a b008 error however in this case it is acceptable because linearcongruentialgenerator __init__ will only be called once per instance and it ensures that each instance will generate a unique sequence of numbers noqa b008 these parameters are saved and used when nextnumber is called modulo is the largest number that can be generated exclusive the most efficient values are powers of 2 2 32 is a common value the smallest number that can be generated is zero the largest number that can be generated is modulo 1 modulo is set in the constructor show the lcg in action
__author__ = "Tobias Carryer" from time import time class LinearCongruentialGenerator: def __init__(self, multiplier, increment, modulo, seed=int(time())): self.multiplier = multiplier self.increment = increment self.modulo = modulo self.seed = seed def next_number(self): self.seed = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": lcg = LinearCongruentialGenerator(1664525, 1013904223, 2 << 31) while True: print(lcg.next_number())
double linked list node built specifically for lru cache doublelinkedlistnode1 1 node key 1 val 1 has next false has prev false double linked list built specifically for lru cache dll doublelinkedlist doublelinkedlist dll doublelinkedlist node key none val none has next true has prev false node key none val none has next false has prev true firstnode doublelinkedlistnode1 10 firstnode node key 1 val 10 has next false has prev false dll addfirstnode dll doublelinkedlist node key none val none has next true has prev false node key 1 val 10 has next true has prev true node key none val none has next false has prev true node is mutated firstnode node key 1 val 10 has next true has prev true secondnode doublelinkedlistnode2 20 secondnode node key 2 val 20 has next false has prev false dll addsecondnode dll doublelinkedlist node key none val none has next true has prev false node key 1 val 10 has next true has prev true node key 2 val 20 has next true has prev true node key none val none has next false has prev true removednode dll removefirstnode assert removednode firstnode dll doublelinkedlist node key none val none has next true has prev false node key 2 val 20 has next true has prev true node key none val none has next false has prev true attempt to remove node not on list removednode dll removefirstnode removednode is none true attempt to remove head or rear dll head node key none val none has next true has prev false dll removedll head is none true attempt to remove head or rear dll rear node key none val none has next false has prev true dll removedll rear is none true adds the given node to the end of the list before rear all nodes other than self head are guaranteed to have nonnone previous removes and returns the given node from the list returns none if node prev or node next is none lru cache to store a given capacity of data can be used as a standalone object or as a function decorator cache lrucache2 cache put1 1 cache put2 2 cache get1 1 cache list doublelinkedlist node key none val none has next true has prev false node key 2 val 2 has next true has prev true node key 1 val 1 has next true has prev true node key none val none has next false has prev true cache cache doctest normalizewhitespace 1 node key 1 val 1 has next true has prev true 2 node key 2 val 2 has next true has prev true cache put3 3 cache list doublelinkedlist node key none val none has next true has prev false node key 1 val 1 has next true has prev true node key 3 val 3 has next true has prev true node key none val none has next false has prev true cache cache doctest normalizewhitespace 1 node key 1 val 1 has next true has prev true 3 node key 3 val 3 has next true has prev true cache get2 is none true cache put4 4 cache get1 is none true cache get3 3 cache get4 4 cache cacheinfohits3 misses2 capacity2 current size2 lrucache decorator100 def fibnum if num in 1 2 return 1 return fibnum 1 fibnum 2 for i in range1 100 res fibi fib cacheinfo cacheinfohits194 misses99 capacity100 current size99 class variable to map the decorator functions to their respective instance return the details for the cache instance hits misses capacity currentsize cache lrucache1 1 in cache false cache put1 1 1 in cache true returns the value for the input key and updates the double linked list returns none if key is not present in cache note pythonic interface would throw keyerror rather than return none node is guaranteed not none because it is in self cache sets the value for the input key and updates the double linked list delete first node oldest when over capacity guaranteed to have a nonnone first node when numkeys 0 explain to type checker via assertions bump node to the end of the list update value decorator version of lru cache decorated function must be function of t u double linked list node built specifically for lru cache doublelinkedlistnode 1 1 node key 1 val 1 has next false has prev false double linked list built specifically for lru cache dll doublelinkedlist doublelinkedlist dll doublelinkedlist node key none val none has next true has prev false node key none val none has next false has prev true first_node doublelinkedlistnode 1 10 first_node node key 1 val 10 has next false has prev false dll add first_node dll doublelinkedlist node key none val none has next true has prev false node key 1 val 10 has next true has prev true node key none val none has next false has prev true node is mutated first_node node key 1 val 10 has next true has prev true second_node doublelinkedlistnode 2 20 second_node node key 2 val 20 has next false has prev false dll add second_node dll doublelinkedlist node key none val none has next true has prev false node key 1 val 10 has next true has prev true node key 2 val 20 has next true has prev true node key none val none has next false has prev true removed_node dll remove first_node assert removed_node first_node dll doublelinkedlist node key none val none has next true has prev false node key 2 val 20 has next true has prev true node key none val none has next false has prev true attempt to remove node not on list removed_node dll remove first_node removed_node is none true attempt to remove head or rear dll head node key none val none has next true has prev false dll remove dll head is none true attempt to remove head or rear dll rear node key none val none has next false has prev true dll remove dll rear is none true adds the given node to the end of the list before rear all nodes other than self head are guaranteed to have non none previous removes and returns the given node from the list returns none if node prev or node next is none lru cache to store a given capacity of data can be used as a stand alone object or as a function decorator cache lrucache 2 cache put 1 1 cache put 2 2 cache get 1 1 cache list doublelinkedlist node key none val none has next true has prev false node key 2 val 2 has next true has prev true node key 1 val 1 has next true has prev true node key none val none has next false has prev true cache cache doctest normalize_whitespace 1 node key 1 val 1 has next true has prev true 2 node key 2 val 2 has next true has prev true cache put 3 3 cache list doublelinkedlist node key none val none has next true has prev false node key 1 val 1 has next true has prev true node key 3 val 3 has next true has prev true node key none val none has next false has prev true cache cache doctest normalize_whitespace 1 node key 1 val 1 has next true has prev true 3 node key 3 val 3 has next true has prev true cache get 2 is none true cache put 4 4 cache get 1 is none true cache get 3 3 cache get 4 4 cache cacheinfo hits 3 misses 2 capacity 2 current size 2 lrucache decorator 100 def fib num if num in 1 2 return 1 return fib num 1 fib num 2 for i in range 1 100 res fib i fib cache_info cacheinfo hits 194 misses 99 capacity 100 current size 99 class variable to map the decorator functions to their respective instance return the details for the cache instance hits misses capacity current_size cache lrucache 1 1 in cache false cache put 1 1 1 in cache true returns the value for the input key and updates the double linked list returns none if key is not present in cache note pythonic interface would throw keyerror rather than return none node is guaranteed not none because it is in self cache sets the value for the input key and updates the double linked list delete first node oldest when over capacity guaranteed to have a non none first node when num_keys 0 explain to type checker via assertions node guaranteed to be in list assert node key is not none bump node to the end of the list update value node guaranteed to be in list decorator version of lru cache decorated function must be function of t u noqa b010
from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode(Generic[T, U]): def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: return ( f"Node: key: {self.key}, val: {self.val}, " f"has next: {bool(self.next)}, has prev: {bool(self.prev)}" ) class DoubleLinkedList(Generic[T, U]): def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: previous = self.rear.prev assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node class LRUCache(Generic[T, U]): decorator_function_to_instance_map: dict[Callable[[T], U], LRUCache[T, U]] = {} def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current size={self.num_keys})" ) def __contains__(self, key: T) -> bool: return key in self.cache def get(self, key: T) -> U | None: if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node assert node is not None self.list.add(node) return node.val self.miss += 1 return None def put(self, key: T, value: U) -> None: if key not in self.cache: if self.num_keys >= self.capacity: first_node = self.list.head.next assert first_node is not None assert first_node.key is not None assert ( self.list.remove(first_node) is not None ) del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: node = self.list.remove(self.cache[key]) assert node is not None node.val = value self.list.add(node) @classmethod def decorator( cls, size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: def cache_decorator_wrapper(*args: T) -> U: if func not in cls.decorator_function_to_instance_map: cls.decorator_function_to_instance_map[func] = LRUCache(size) result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) cls.decorator_function_to_instance_map[func].put(args[0], result) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(cache_decorator_wrapper, "cache_info", cache_info) return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
python program for generating diamond pattern in python 3 7 function to print upper half of diamond pyramid print the upper half of a diamond pattern with characters args n int size of the pattern examples floyd3 n n n floyd5 n n n n n function to print lower half of diamond pyramid print the lower half of a diamond pattern with characters args n int size of the pattern examples reversefloyd3 n n n reversefloyd5 n n n n n function to print complete diamond pattern of print a complete diamond pattern with characters args n int size of the pattern examples prettyprint0 nothing printing prettyprint3 n n n n n n python program for generating diamond pattern in python 3 7 function to print upper half of diamond pyramid print the upper half of a diamond pattern with characters args n int size of the pattern examples floyd 3 n n n floyd 5 n n n n n printing spaces printing stars function to print lower half of diamond pyramid print the lower half of a diamond pattern with characters args n int size of the pattern examples reverse_floyd 3 n n n reverse_floyd 5 n n n n n printing stars printing spaces function to print complete diamond pattern of print a complete diamond pattern with characters args n int size of the pattern examples pretty_print 0 nothing printing pretty_print 3 n n n n n n upper half lower half
def floyd(n): result = "" for i in range(n): for _ in range(n - i - 1): result += " " for _ in range(i + 1): result += "* " result += "\n" return result def reverse_floyd(n): result = "" for i in range(n, 0, -1): for _ in range(i, 0, -1): result += "* " result += "\n" for _ in range(n - i + 1, 0, -1): result += " " return result def pretty_print(n): if n <= 0: return " ... .... nothing printing :(" upper_half = floyd(n) lower_half = reverse_floyd(n) return upper_half + lower_half if __name__ == "__main__": import doctest doctest.testmod()
this is booyermoore majority vote algorithm the problem statement goes like this given an integer array of size n find all elements that appear more than nk times we have to solve in on time and o1 space url https en wikipedia orgwikiboyere28093mooremajorityvotealgorithm majorityvote1 2 2 3 1 3 2 3 2 majorityvote1 2 2 3 1 3 2 2 majorityvote1 2 2 3 1 3 2 4 1 2 3 majority_vote 1 2 2 3 1 3 2 3 2 majority_vote 1 2 2 3 1 3 2 2 majority_vote 1 2 2 3 1 3 2 4 1 2 3
from collections import Counter def majority_vote(votes: list[int], votes_needed_to_win: int) -> list[int]: majority_candidate_counter: Counter[int] = Counter() for vote in votes: majority_candidate_counter[vote] += 1 if len(majority_candidate_counter) == votes_needed_to_win: majority_candidate_counter -= Counter(set(majority_candidate_counter)) majority_candidate_counter = Counter( vote for vote in votes if vote in majority_candidate_counter ) return [ vote for vote in majority_candidate_counter if majority_candidate_counter[vote] > len(votes) / votes_needed_to_win ] if __name__ == "__main__": import doctest doctest.testmod()
return the maximum possible sum amongst all non empty subsequences raises valueerror when nums is empty maxsubsequencesum1 2 3 4 2 10 maxsubsequencesum2 3 1 4 6 1 maxsubsequencesum traceback most recent call last valueerror input sequence should not be empty maxsubsequencesum traceback most recent call last valueerror input sequence should not be empty try on a sample input from the user return the maximum possible sum amongst all non empty subsequences raises valueerror when nums is empty max_subsequence_sum 1 2 3 4 2 10 max_subsequence_sum 2 3 1 4 6 1 max_subsequence_sum traceback most recent call last valueerror input sequence should not be empty max_subsequence_sum traceback most recent call last valueerror input sequence should not be empty try on a sample input from the user
from collections.abc import Sequence def max_subsequence_sum(nums: Sequence[int] | None = None) -> int: if nums is None or not nums: raise ValueError("Input sequence should not be empty") ans = nums[0] for i in range(1, len(nums)): num = nums[i] ans = max(ans, ans + num, num) return ans if __name__ == "__main__": import doctest doctest.testmod() n = int(input("Enter number of elements : ").strip()) array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] print(max_subsequence_sum(array))
the nested brackets problem is a problem that determines if a sequence of brackets are properly nested a sequence of brackets s is considered properly nested if any of the following conditions are true s is empty s has the form u or u or u where u is a properly nested string s has the form vw where v and w are properly nested strings for example the string is properly nested but is not the function called isbalanced takes as input a string s which is a sequence of brackets and returns true if s is nested and false otherwise isbalanced true isbalanced true isbalanced true isbalanced true isbalanced true isbalanced true isbalanced false isbalanced true isbalanced false isbalanced false isbalanced true isbalanced true isbalanced false isbalancedlife is a bowl of cherries true isbalancedlife is a bowl of cheies true isbalancedlife is a bowl of cheies false is_balanced true is_balanced true is_balanced true is_balanced true is_balanced true is_balanced true is_balanced false is_balanced true is_balanced false is_balanced false is_balanced true is_balanced true is_balanced false is_balanced life is a bowl of cherries true is_balanced life is a bowl of che ies true is_balanced life is a bowl of che ies false stack should be empty
def is_balanced(s: str) -> bool: open_to_closed = {"{": "}", "[": "]", "(": ")"} stack = [] for symbol in s: if symbol in open_to_closed: stack.append(symbol) elif symbol in open_to_closed.values() and ( not stack or open_to_closed[stack.pop()] != symbol ): return False return not stack def main(): s = input("Enter sequence of brackets: ") print(f"'{s}' is {'' if is_balanced(s) else 'not '}balanced.") if __name__ == "__main__": from doctest import testmod testmod() main()
a number container system that uses binary search to delete and insert values into arrays with olog n write times and o1 read times this container system holds integers at indexes further explained in this leetcode problem https leetcode comproblemsminimumcosttreefromleafvalues numbermap keys are the number and its values are lists of indexes sorted in ascending order indexmap keys are an index and it s values are the number at that index removes the item from the sorted array and returns the new array numbercontainer binarysearchdelete1 2 3 2 1 3 numbercontainer binarysearchdelete0 0 0 0 0 0 numbercontainer binarysearchdelete1 1 1 1 1 1 numbercontainer binarysearchdelete1 0 0 1 numbercontainer binarysearchdelete1 0 1 0 numbercontainer binarysearchdeleterange7 3 0 1 2 4 5 6 numbercontainer binarysearchdelete1 1 2 2 3 3 2 2 1 1 3 3 numbercontainer binarysearchdeleteabcde c a b d e numbercontainer binarysearchdelete0 1 2 4 0 traceback most recent call last valueerror either the item is not in the array or the array was unsorted numbercontainer binarysearchdelete2 0 4 1 11 1 traceback most recent call last valueerror either the item is not in the array or the array was unsorted numbercontainer binarysearchdelete125 1 traceback most recent call last typeerror binarysearchdelete only accepts either a list range or str inserts the index into the sorted array at the correct position numbercontainer binarysearchinsert1 2 3 2 1 2 2 3 numbercontainer binarysearchinsert0 1 3 2 0 1 2 3 numbercontainer binarysearchinsert5 3 0 0 11 103 51 5 3 0 0 11 51 103 numbercontainer binarysearchinsert5 3 0 0 11 100 103 101 5 3 0 0 11 100 101 103 numbercontainer binarysearchinsertrange10 4 0 1 2 3 4 4 5 6 7 8 9 numbercontainer binarysearchinsertabd c a b c d numbercontainer binarysearchinsert131 23 traceback most recent call last typeerror binarysearchinsert only accepts either a list range or str if the item already exists in the array insert it after the existing item if the item doesn t exist in the array insert it at the appropriate position changes sets the index as number cont numbercontainer cont change0 10 cont change0 20 cont change13 20 cont change100030 20032903290 remove previous index set new index number not seen before or empty so insert number value here we need to perform a binary search insertion in order to insert the item in the correct place returns the smallest index where the number is cont numbercontainer cont find10 1 cont change0 10 cont find10 0 cont change0 20 cont find10 1 cont find20 0 simply return the 0th index smallest of the indexes found or 1 numbermap keys are the number and its values are lists of indexes sorted in ascending order indexmap keys are an index and it s values are the number at that index removes the item from the sorted array and returns the new array numbercontainer binary_search_delete 1 2 3 2 1 3 numbercontainer binary_search_delete 0 0 0 0 0 0 numbercontainer binary_search_delete 1 1 1 1 1 1 numbercontainer binary_search_delete 1 0 0 1 numbercontainer binary_search_delete 1 0 1 0 numbercontainer binary_search_delete range 7 3 0 1 2 4 5 6 numbercontainer binary_search_delete 1 1 2 2 3 3 2 2 1 1 3 3 numbercontainer binary_search_delete abcde c a b d e numbercontainer binary_search_delete 0 1 2 4 0 traceback most recent call last valueerror either the item is not in the array or the array was unsorted numbercontainer binary_search_delete 2 0 4 1 11 1 traceback most recent call last valueerror either the item is not in the array or the array was unsorted numbercontainer binary_search_delete 125 1 traceback most recent call last typeerror binary_search_delete only accepts either a list range or str inserts the index into the sorted array at the correct position numbercontainer binary_search_insert 1 2 3 2 1 2 2 3 numbercontainer binary_search_insert 0 1 3 2 0 1 2 3 numbercontainer binary_search_insert 5 3 0 0 11 103 51 5 3 0 0 11 51 103 numbercontainer binary_search_insert 5 3 0 0 11 100 103 101 5 3 0 0 11 100 101 103 numbercontainer binary_search_insert range 10 4 0 1 2 3 4 4 5 6 7 8 9 numbercontainer binary_search_insert abd c a b c d numbercontainer binary_search_insert 131 23 traceback most recent call last typeerror binary_search_insert only accepts either a list range or str if the item already exists in the array insert it after the existing item if the item doesn t exist in the array insert it at the appropriate position changes sets the index as number cont numbercontainer cont change 0 10 cont change 0 20 cont change 13 20 cont change 100030 20032903290 remove previous index set new index number not seen before or empty so insert number value here we need to perform a binary search insertion in order to insert the item in the correct place returns the smallest index where the number is cont numbercontainer cont find 10 1 cont change 0 10 cont find 10 0 cont change 0 20 cont find 10 1 cont find 20 0 simply return the 0th index smallest of the indexes found or 1
class NumberContainer: def __init__(self) -> None: self.numbermap: dict[int, list[int]] = {} self.indexmap: dict[int, int] = {} def binary_search_delete(self, array: list | str | range, item: int) -> list[int]: if isinstance(array, (range, str)): array = list(array) elif not isinstance(array, list): raise TypeError( "binary_search_delete() only accepts either a list, range or str" ) low = 0 high = len(array) - 1 while low <= high: mid = (low + high) // 2 if array[mid] == item: array.pop(mid) return array elif array[mid] < item: low = mid + 1 else: high = mid - 1 raise ValueError( "Either the item is not in the array or the array was unsorted" ) def binary_search_insert(self, array: list | str | range, index: int) -> list[int]: if isinstance(array, (range, str)): array = list(array) elif not isinstance(array, list): raise TypeError( "binary_search_insert() only accepts either a list, range or str" ) low = 0 high = len(array) - 1 while low <= high: mid = (low + high) // 2 if array[mid] == index: array.insert(mid + 1, index) return array elif array[mid] < index: low = mid + 1 else: high = mid - 1 array.insert(low, index) return array def change(self, index: int, number: int) -> None: if index in self.indexmap: n = self.indexmap[index] if len(self.numbermap[n]) == 1: del self.numbermap[n] else: self.numbermap[n] = self.binary_search_delete(self.numbermap[n], index) self.indexmap[index] = number if number not in self.numbermap: self.numbermap[number] = [index] else: self.numbermap[number] = self.binary_search_insert( self.numbermap[number], index ) def find(self, number: int) -> int: return self.numbermap.get(number, [-1])[0] if __name__ == "__main__": import doctest doctest.testmod()
password generator allows you to generate a random password of length n lenpasswordgenerator 8 lenpasswordgeneratorlength16 16 lenpasswordgenerator257 257 lenpasswordgeneratorlength0 0 lenpasswordgenerator1 0 alternative methods charsincl characters that must be in password i how many letters or characters the password length will be password generator full boot with randomnumber randomletters and randomcharacter functions put your code here chars charsincl randomlettersasciiletters i 3 remainder randomnumberdigits i 3 randomcharacterspunctuation i 3 random is a generalised function for letters characters and numbers this will check whether a given password is strong or not the password must be at least as long as the provided minimum length and it must contain at least 1 lowercase letter 1 uppercase letter 1 number and 1 special character isstrongpassword hwea72 true isstrongpassword sh0r1 false isstrongpassword hello123 false isstrongpassword hello1238udfhiaf038fajdvjjf jaiufhkqi1 true isstrongpassword 0 false password generator allows you to generate a random password of length n len password_generator 8 len password_generator length 16 16 len password_generator 257 257 len password_generator length 0 0 len password_generator 1 0 alternative methods chars_incl characters that must be in password i how many letters or characters the password length will be password generator full boot with random_number random_letters and random_character functions put your code here chars chars_incl random_letters ascii_letters i 3 remainder random_number digits i 3 random_characters punctuation i 3 random is a generalised function for letters characters and numbers put your code here put your code here put your code here this will check whether a given password is strong or not the password must be at least as long as the provided minimum length and it must contain at least 1 lowercase letter 1 uppercase letter 1 number and 1 special character is_strong_password hwea7 2 true is_strong_password sh0r1 false is_strong_password hello123 false is_strong_password hello1238udfhiaf038fajdvjjf jaiufhkqi1 true is_strong_password 0 false
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def password_generator(length: int = 8) -> str: chars = ascii_letters + digits + punctuation return "".join(secrets.choice(chars) for _ in range(length)) def alternative_password_generator(chars_incl: str, i: int) -> str: i -= len(chars_incl) quotient = i // 3 remainder = i % 3 chars = ( chars_incl + random(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient) ) list_of_chars = list(chars) shuffle(list_of_chars) return "".join(list_of_chars) def random(chars_incl: str, i: int) -> str: return "".join(secrets.choice(chars_incl) for _ in range(i)) def random_number(chars_incl, i): pass def random_letters(chars_incl, i): pass def random_characters(chars_incl, i): pass def is_strong_password(password: str, min_length: int = 8) -> bool: if len(password) < min_length: return False upper = any(char in ascii_uppercase for char in password) lower = any(char in ascii_lowercase for char in password) num = any(char in digits for char in password) spec_char = any(char in punctuation for char in password) return upper and lower and num and spec_char def main(): length = int(input("Please indicate the max length of your password: ").strip()) chars_incl = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:", password_generator(length)) print( "Alternative Password generated:", alternative_password_generator(chars_incl, length), ) print("[If you are thinking of using this password, You better save it.]") if __name__ == "__main__": main()
binpython3 ruff noqa quine a quine is a computer program which takes no input and produces a copy of its own source code as its only output disregarding this docstring and the shebang more info on https en wikipedia orgwikiquinecomputing bin python3 ruff noqa quine a quine is a computer program which takes no input and produces a copy of its own source code as its only output disregarding this docstring and the shebang more info on https en wikipedia org wiki quine_ computing
print((lambda quine: quine % quine)("print((lambda quine: quine %% quine)(%r))"))
developed by markmelnic original repo https github commarkmelnicscoringalgorithm analyse data using a range based percentual proximity algorithm and calculate the linear maximum likelihood estimation the basic principle is that all values supplied will be broken down to a range from 0 to 1 and each column s score will be added up to get the total score example for data of vehicles pricemileageregistrationyear 20k 60k 2012 22k 50k 2011 23k 90k 2015 16k 210k 2010 we want the vehicle with the lowest price lowest mileage but newest registration year thus the weights for each column are as follows 0 0 1 getdata20 60 2012 23 90 2015 22 50 2011 20 0 23 0 22 0 60 0 90 0 50 0 2012 0 2015 0 2011 0 calculateeachscore20 23 22 60 90 50 2012 2015 2011 0 0 1 1 0 0 0 0 33333333333333337 0 75 0 0 1 0 0 25 1 0 0 0 for weight 0 score is 1 actual score weight not 0 or 1 generatefinalscores1 0 0 0 0 33333333333333337 0 75 0 0 1 0 0 25 1 0 0 0 2 0 1 0 1 3333333333333335 initialize final scores weights int list possible values 0 1 0 if lower values have higher weight in the data set 1 if higher values have higher weight in the data set procentualproximity20 60 2012 23 90 2015 22 50 2011 0 0 1 20 60 2012 2 0 23 90 2015 1 0 22 50 2011 1 3333333333333335 append scores to source data get_data 20 60 2012 23 90 2015 22 50 2011 20 0 23 0 22 0 60 0 90 0 50 0 2012 0 2015 0 2011 0 calculate_each_score 20 23 22 60 90 50 2012 2015 2011 0 0 1 1 0 0 0 0 33333333333333337 0 75 0 0 1 0 0 25 1 0 0 0 for weight 0 score is 1 actual score weight not 0 or 1 generate_final_scores 1 0 0 0 0 33333333333333337 0 75 0 0 1 0 0 25 1 0 0 0 2 0 1 0 1 3333333333333335 initialize final scores weights int list possible values 0 1 0 if lower values have higher weight in the data set 1 if higher values have higher weight in the data set procentual_proximity 20 60 2012 23 90 2015 22 50 2011 0 0 1 20 60 2012 2 0 23 90 2015 1 0 22 50 2011 1 3333333333333335 append scores to source data
def get_data(source_data: list[list[float]]) -> list[list[float]]: data_lists: list[list[float]] = [] for data in source_data: for i, el in enumerate(data): if len(data_lists) < i + 1: data_lists.append([]) data_lists[i].append(float(el)) return data_lists def calculate_each_score( data_lists: list[list[float]], weights: list[int] ) -> list[list[float]]: score_lists: list[list[float]] = [] for dlist, weight in zip(data_lists, weights): mind = min(dlist) maxd = max(dlist) score: list[float] = [] if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind))) except ZeroDivisionError: score.append(1) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind)) except ZeroDivisionError: score.append(0) else: msg = f"Invalid weight of {weight:f} provided" raise ValueError(msg) score_lists.append(score) return score_lists def generate_final_scores(score_lists: list[list[float]]) -> list[float]: final_scores: list[float] = [0 for i in range(len(score_lists[0]))] for slist in score_lists: for j, ele in enumerate(slist): final_scores[j] = final_scores[j] + ele return final_scores def procentual_proximity( source_data: list[list[float]], weights: list[int] ) -> list[list[float]]: data_lists = get_data(source_data) score_lists = calculate_each_score(data_lists, weights) final_scores = generate_final_scores(score_lists) for i, ele in enumerate(final_scores): source_data[i].append(ele) return source_data
applytable0123456789 listrange10 9012345678 applytable0123456789 listrange9 1 1 8765432109 leftshift0123456789 1234567890 xor01010101 00001111 01011010 key generation encryption decryption apply_table 0123456789 list range 10 9012345678 apply_table 0123456789 list range 9 1 1 8765432109 left_shift 0123456789 1234567890 xor 01010101 00001111 01011010 noqa e741 noqa e741 key generation encryption decryption
def apply_table(inp, table): res = "" for i in table: res += inp[i - 1] return res def left_shift(data): return data[1:] + data[0] def xor(a, b): res = "" for i in range(len(a)): if a[i] == b[i]: res += "0" else: res += "1" return res def apply_sbox(s, data): row = int("0b" + data[0] + data[-1], 2) col = int("0b" + data[1:3], 2) return bin(s[row][col])[2:] def function(expansion, s0, s1, key, message): left = message[:4] right = message[4:] temp = apply_table(right, expansion) temp = xor(temp, key) l = apply_sbox(s0, temp[:4]) r = apply_sbox(s1, temp[4:]) l = "0" * (2 - len(l)) + l r = "0" * (2 - len(r)) + r temp = apply_table(l + r, p4_table) temp = xor(left, temp) return temp + right if __name__ == "__main__": key = input("Enter 10 bit key: ") message = input("Enter 8 bit message: ") p8_table = [6, 3, 7, 4, 8, 5, 10, 9] p10_table = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] p4_table = [2, 4, 3, 1] IP = [2, 6, 3, 1, 4, 8, 5, 7] IP_inv = [4, 1, 3, 5, 7, 2, 8, 6] expansion = [4, 1, 2, 3, 2, 3, 4, 1] s0 = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] s1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] temp = apply_table(key, p10_table) left = temp[:5] right = temp[5:] left = left_shift(left) right = left_shift(right) key1 = apply_table(left + right, p8_table) left = left_shift(left) right = left_shift(right) left = left_shift(left) right = left_shift(right) key2 = apply_table(left + right, p8_table) temp = apply_table(message, IP) temp = function(expansion, s0, s1, key1, temp) temp = temp[4:] + temp[:4] temp = function(expansion, s0, s1, key2, temp) CT = apply_table(temp, IP_inv) print("Cipher text is:", CT) temp = apply_table(CT, IP) temp = function(expansion, s0, s1, key2, temp) temp = temp[4:] + temp[:4] temp = function(expansion, s0, s1, key1, temp) PT = apply_table(temp, IP_inv) print("Plain text after decypting is:", PT)
movetower3 a b c moving disk from a to b moving disk from a to c moving disk from b to c moving disk from a to b moving disk from c to a moving disk from c to b moving disk from a to b move_tower 3 a b c moving disk from a to b moving disk from a to c moving disk from b to c moving disk from a to b moving disk from c to a moving disk from c to b moving disk from a to b
def move_tower(height, from_pole, to_pole, with_pole): if height >= 1: move_tower(height - 1, from_pole, with_pole, to_pole) move_disk(from_pole, to_pole) move_tower(height - 1, with_pole, to_pole, from_pole) def move_disk(fp, tp): print("moving disk from", fp, "to", tp) def main(): height = int(input("Height of hanoi: ").strip()) move_tower(height, "A", "B", "C") if __name__ == "__main__": main()
title calculate altitude using pressure description the below algorithm approximates the altitude using barometric formula this method calculates the altitude from pressure wrt to sea level pressure as reference pressure is in pascals https en wikipedia orgwikipressurealtitude https community boschsensortec comt5questionandanswershowtocalculatethealtitudefromthepressuresensordataqaqp5702 h 44330 1 pp015 255 where h altitude m p measured pressure p0 reference pressure at sea level 101325 pa examples getaltitudeatpressurepressure100000 105 47836610778828 getaltitudeatpressurepressure101325 0 0 getaltitudeatpressurepressure80000 1855 873388064995 getaltitudeatpressurepressure201325 traceback most recent call last valueerror value higher than pressure at sea level getaltitudeatpressurepressure80000 traceback most recent call last valueerror atmospheric pressure can not be negative this method calculates the altitude from pressure wrt to sea level pressure as reference pressure is in pascals https en wikipedia org wiki pressure_altitude https community bosch sensortec com t5 question and answers how to calculate the altitude from the pressure sensor data qaq p 5702 h 44330 1 p p0 1 5 255 where h altitude m p measured pressure p0 reference pressure at sea level 101325 pa examples get_altitude_at_pressure pressure 100_000 105 47836610778828 get_altitude_at_pressure pressure 101_325 0 0 get_altitude_at_pressure pressure 80_000 1855 873388064995 get_altitude_at_pressure pressure 201_325 traceback most recent call last valueerror value higher than pressure at sea level get_altitude_at_pressure pressure 80_000 traceback most recent call last valueerror atmospheric pressure can not be negative
def get_altitude_at_pressure(pressure: float) -> float: if pressure > 101325: raise ValueError("Value Higher than Pressure at Sea Level !") if pressure < 0: raise ValueError("Atmospheric Pressure can not be negative !") return 44_330 * (1 - (pressure / 101_325) ** (1 / 5.5255)) if __name__ == "__main__": import doctest doctest.testmod()
calculate the buoyant force of any body completely or partially submerged in a static fluid this principle was discovered by the greek mathematician archimedes equation for calculating buoyant force fb v g https en wikipedia orgwikiarchimedes27principle acceleration constant on earth unit ms2 args fluiddensity density of fluid kgm3 volume volume of objectliquid being displaced by the object m3 gravity acceleration from gravity gravitational force on the system the default is earth gravity returns the buoyant force on an object in newtons archimedesprinciplefluiddensity500 volume4 gravity9 8 19600 0 archimedesprinciplefluiddensity997 volume0 5 gravity9 8 4885 3 archimedesprinciplefluiddensity997 volume0 7 6844 061035 archimedesprinciplefluiddensity997 volume0 7 traceback most recent call last valueerror impossible object volume archimedesprinciplefluiddensity0 volume0 7 traceback most recent call last valueerror impossible fluid density archimedesprinciplefluiddensity997 volume0 7 gravity0 0 0 archimedesprinciplefluiddensity997 volume0 7 gravity9 8 traceback most recent call last valueerror impossible gravity acceleration constant on earth unit m s 2 also available in scipy constants g args fluid_density density of fluid kg m 3 volume volume of object liquid being displaced by the object m 3 gravity acceleration from gravity gravitational force on the system the default is earth gravity returns the buoyant force on an object in newtons archimedes_principle fluid_density 500 volume 4 gravity 9 8 19600 0 archimedes_principle fluid_density 997 volume 0 5 gravity 9 8 4885 3 archimedes_principle fluid_density 997 volume 0 7 6844 061035 archimedes_principle fluid_density 997 volume 0 7 traceback most recent call last valueerror impossible object volume archimedes_principle fluid_density 0 volume 0 7 traceback most recent call last valueerror impossible fluid density archimedes_principle fluid_density 997 volume 0 7 gravity 0 0 0 archimedes_principle fluid_density 997 volume 0 7 gravity 9 8 traceback most recent call last valueerror impossible gravity
g = 9.80665 def archimedes_principle( fluid_density: float, volume: float, gravity: float = g ) -> float: if fluid_density <= 0: raise ValueError("Impossible fluid density") if volume <= 0: raise ValueError("Impossible object volume") if gravity < 0: raise ValueError("Impossible gravity") return fluid_density * gravity * volume if __name__ == "__main__": import doctest doctest.testmod()
these two functions will return the radii of impact for a target object of mass m and radius r as well as it s effective cross sectional area sigma that is to say any projectile with velocity v passing within will impact the target object with mass m the derivation of which is given at the bottom of this file the derivation shows that a projectile does not need to aim directly at the target body in order to hit it as rcapturertarget astronomers refer to the effective cross section for capture as rcapture2 this algorithm does not account for an nbody problem input params targetbodyradius radius of the central body si units meters m targetbodymass mass of the central body si units kilograms kg projectilevelocity velocity of object moving toward central body si units meterssecond ms returns captureradii6 957e8 1 99e30 25000 0 17209590691 0 captureradii6 957e8 1 99e30 25000 0 traceback most recent call last valueerror radius cannot be less than 0 captureradii6 957e8 1 99e30 25000 0 traceback most recent call last valueerror mass cannot be less than 0 captureradii6 957e8 1 99e30 c1 traceback most recent call last valueerror cannot go beyond speed of light returned si units meters m input param captureradius the radius of orbital capture and impact for a central body of mass m and a projectile moving towards it with velocity v si units meters m returns capturearea17209590691 9 304455331329126e20 capturearea1 traceback most recent call last valueerror cannot have a capture radius less than 0 returned si units metersmeters m2 derivation let mttarget mass rttarget radius vprojectilevelocity r0radius of projectile at instant 0 to cm of target vpv at closest approach rpradius from projectile to target cm at closest approach rcapture radius of impact for projectile with velocity v 1at time0 the projectile s energy falling from infinity eku0 5mv20 einitial0 5mv2 2at time0 the angular momentum of the projectile relative to cm target linitialmr0vsinmr0vrcapturer0mvrcapture limvrcapture 3the energy of the projectile at closest approach will be its kinetic energy at closest approach plus gravitational potential energygmmr epkpupep0 5mvp2gmtmrp ep0 0 5mvp2gmtmrp 4the angular momentum of the projectile relative to the target at closest approach will be lpmrpvpsin however relative to the target 90 sin901 lpmrpvp 5using conservation of angular momentum and energy we can write a quadratic equation that solves for rp a eiep 0 5mv20 5mvp2gmtmrp v2vp22gmtrp b lilp mvrcapturemrpvp vrcapturerpvp vpvrcapturerp c b plugs int a v2vrcapturerp22gmtrp v2v2rc2rp22gmtrp0 v2rp22gmtrpv2rc20 d using the quadratic formula we ll solve for rp then rearrange to solve to rcapture rp2gmt sqrt4g2mt2 4v4rc22v2 rpgmt sqrtg2mtv4rc2v2 rp0 is something we can ignore as it has no physical meaning for our purposes rpgmtv2 sqrtg2mt2v4 rc2 ewe are trying to solve for rc we are looking for impact so we want rprt rt gmtv2 sqrtg2mt2v4 rc2 rt gmtv22 g2mt2v4 rc2 rt2 2gmtrtv2 g2mt2v4 g2mt2v4 rc2 rt2 2gmtrtv2 rc2 rt2 1 2gmtrt 1v2 rc2 escape velocity sqrt2gmr vescape22gmr rt2 1 vesc2v2 rc2 6 rcapture rt sqrt1 vesc2v2 source problem set 3 8 c fall2017honors astronomyprofessor rachel bezanson source 2 http www nssc ac cnwxzygxweixin201607p020160718380095698873 pdf 8 8 planetary rendezvous pg 368 these two functions will return the radii of impact for a target object of mass m and radius r as well as it s effective cross sectional area σ sigma that is to say any projectile with velocity v passing within σ will impact the target object with mass m the derivation of which is given at the bottom of this file the derivation shows that a projectile does not need to aim directly at the target body in order to hit it as r_capture r_target astronomers refer to the effective cross section for capture as σ π r_capture 2 this algorithm does not account for an n body problem input params target_body_radius radius of the central body si units meters m target_body_mass mass of the central body si units kilograms kg projectile_velocity velocity of object moving toward central body si units meters second m s returns capture_radii 6 957e8 1 99e30 25000 0 17209590691 0 capture_radii 6 957e8 1 99e30 25000 0 traceback most recent call last valueerror radius cannot be less than 0 capture_radii 6 957e8 1 99e30 25000 0 traceback most recent call last valueerror mass cannot be less than 0 capture_radii 6 957e8 1 99e30 c 1 traceback most recent call last valueerror cannot go beyond speed of light returned si units meters m input param capture_radius the radius of orbital capture and impact for a central body of mass m and a projectile moving towards it with velocity v si units meters m returns capture_area 17209590691 9 304455331329126e 20 capture_area 1 traceback most recent call last valueerror cannot have a capture radius less than 0 returned si units meters meters m 2 derivation let mt target mass rt target radius v projectile_velocity r_0 radius of projectile at instant 0 to cm of target v_p v at closest approach r_p radius from projectile to target cm at closest approach r_capture radius of impact for projectile with velocity v 1 at time 0 the projectile s energy falling from infinity e k u 0 5 m v 2 0 e_initial 0 5 m v 2 2 at time 0 the angular momentum of the projectile relative to cm target l_initial m r_0 v sin θ m r_0 v r_capture r_0 m v r_capture l_i m v r_capture 3 the energy of the projectile at closest approach will be its kinetic energy at closest approach plus gravitational potential energy gmm r e_p k_p u_p e_p 0 5 m v_p 2 g mt m r_p e_p 0 0 5 m v_p 2 g mt m r_p 4 the angular momentum of the projectile relative to the target at closest approach will be l_p m r_p v_p sin θ however relative to the target θ 90 sin 90 1 l_p m r_p v_p 5 using conservation of angular momentum and energy we can write a quadratic equation that solves for r_p a ei ep 0 5 m v 2 0 5 m v_p 2 g mt m r_p v 2 v_p 2 2 g mt r_p b li lp m v r_capture m r_p v_p v r_capture r_p v_p v_p v r_capture r_p c b plugs int a v 2 v r_capture r_p 2 2 g mt r_p v 2 v 2 r_c 2 r_p 2 2 g mt r_p 0 v 2 r_p 2 2 g mt r_p v 2 r_c 2 0 d using the quadratic formula we ll solve for r_p then rearrange to solve to r_capture r_p 2 g mt sqrt 4 g 2 mt 2 4 v 4 r_c 2 2 v 2 r_p g mt sqrt g 2 mt v 4 r_c 2 v 2 r_p 0 is something we can ignore as it has no physical meaning for our purposes r_p g mt v 2 sqrt g 2 mt 2 v 4 r_c 2 e we are trying to solve for r_c we are looking for impact so we want r_p rt rt g mt v 2 sqrt g 2 mt 2 v 4 r_c 2 rt g mt v 2 2 g 2 mt 2 v 4 r_c 2 rt 2 2 g mt rt v 2 g 2 mt 2 v 4 g 2 mt 2 v 4 r_c 2 rt 2 2 g mt rt v 2 r_c 2 rt 2 1 2 g mt rt 1 v 2 r_c 2 escape velocity sqrt 2gm r v_escape 2 2gm r rt 2 1 v_esc 2 v 2 r_c 2 6 r_capture rt sqrt 1 v_esc 2 v 2 source problem set 3 8 c fall_2017 honors astronomy professor rachel bezanson source 2 http www nssc ac cn wxzygx weixin 201607 p020160718380095698873 pdf 8 8 planetary rendezvous pg 368
from math import pow, sqrt from scipy.constants import G, c, pi def capture_radii( target_body_radius: float, target_body_mass: float, projectile_velocity: float ) -> float: if target_body_mass < 0: raise ValueError("Mass cannot be less than 0") if target_body_radius < 0: raise ValueError("Radius cannot be less than 0") if projectile_velocity > c: raise ValueError("Cannot go beyond speed of light") escape_velocity_squared = (2 * G * target_body_mass) / target_body_radius capture_radius = target_body_radius * sqrt( 1 + escape_velocity_squared / pow(projectile_velocity, 2) ) return round(capture_radius, 0) def capture_area(capture_radius: float) -> float: if capture_radius < 0: raise ValueError("Cannot have a capture radius less than 0") sigma = pi * pow(capture_radius, 2) return round(sigma, 0) if __name__ == "__main__": from doctest import testmod testmod()
title finding the value of magnitude of either the casimir force the surface area of one of the plates or distance between the plates provided that the other two parameters are given description in quantum field theory the casimir effect is a physical force acting on the macroscopic boundaries of a confined space which arises from the quantum fluctuations of the field it is a physical force exerted between separate objects which is due to neither charge gravity nor the exchange of particles but instead is due to resonance of allpervasive energy fields in the intervening space between the objects since the strength of the force falls off rapidly with distance it is only measurable when the distance between the objects is extremely small on a submicron scale this force becomes so strong that it becomes the dominant force between uncharged conductors dutch physicist hendrik b g casimir first proposed the existence of the force and he formulated an experiment to detect it in 1948 while participating in research at philips research labs the classic form of his experiment used a pair of uncharged parallel metal plates in a vacuum and successfully demonstrated the force to within 15 of the value he had predicted according to his theory the casimir force f for idealized perfectly conducting plates of surface area a square meter and placed at a distance of a meter apart with vacuum between them is expressed as f reduced planck constant c pi2 a 240 a4 here the negative sign indicates the force is attractive in nature for the ease of calculation only the magnitude of the force is considered source https en wikipedia orgwikicasimireffect https www cs mcgill carwestwikispeediawpcdwpccasimireffect htm casimir h b polder d 1948 the influence of retardation on the londonvan der waals forces physical review vol 73 issue 4 pp 360372 define the reduced planck constant h bar speed of light c value of pi and the function input parameters force casimir force magnitude in newtons area surface area of each plate magnitude in square meters distance distance between two plates distance in meters returns result dict name value pair of the parameter having zero as it s value returns the value of one of the parameters specified as 0 provided the values of other parameters are given casimirforceforce 0 area 4 distance 0 03 force 6 4248189174864216e21 casimirforceforce 2635e13 area 0 0023 distance 0 distance 1 0323056015031114e05 casimirforceforce 2737e21 area 0 distance 0 0023746 area 0 06688838837354052 casimirforceforce 3457e12 area 0 distance 0 traceback most recent call last valueerror one and only one argument must be 0 casimirforceforce 3457e12 area 0 distance 0 00344 traceback most recent call last valueerror distance can not be negative casimirforceforce 912e12 area 0 distance 0 09374 traceback most recent call last valueerror magnitude of force can not be negative run doctest define the reduced planck constant ℏ h bar speed of light c value of pi and the function unit of ℏ j s unit of c m s 1 input parameters force casimir force magnitude in newtons area surface area of each plate magnitude in square meters distance distance between two plates distance in meters returns result dict name value pair of the parameter having zero as it s value returns the value of one of the parameters specified as 0 provided the values of other parameters are given casimir_force force 0 area 4 distance 0 03 force 6 4248189174864216e 21 casimir_force force 2635e 13 area 0 0023 distance 0 distance 1 0323056015031114e 05 casimir_force force 2737e 21 area 0 distance 0 0023746 area 0 06688838837354052 casimir_force force 3457e 12 area 0 distance 0 traceback most recent call last valueerror one and only one argument must be 0 casimir_force force 3457e 12 area 0 distance 0 00344 traceback most recent call last valueerror distance can not be negative casimir_force force 912e 12 area 0 distance 0 09374 traceback most recent call last valueerror magnitude of force can not be negative run doctest
from __future__ import annotations from math import pi REDUCED_PLANCK_CONSTANT = 1.054571817e-34 SPEED_OF_LIGHT = 3e8 def casimir_force(force: float, area: float, distance: float) -> dict[str, float]: if (force, area, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Magnitude of force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if area < 0: raise ValueError("Area can not be negative") if force == 0: force = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: area = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: distance = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError("One and only one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
calculating the center of mass for a discrete system of particles given their positions and masses description in physics the center of mass of a distribution of mass in space sometimes referred to as the barycenter or balance point is the unique point at any given time where the weighted relative position of the distributed mass sums to zero this is the point to which a force may be applied to cause a linear acceleration without an angular acceleration calculations in mechanics are often simplified when formulated with respect to the center of mass it is a hypothetical point where the entire mass of an object may be assumed to be concentrated to visualize its motion in other words the center of mass is the particle equivalent of a given object for the application of newton s laws of motion in the case of a system of particles pi i 1 n each with mass mi that are located in space with coordinates ri i 1 n the coordinates r of the center of mass corresponds to r mi ri mi reference https en wikipedia orgwikicenterofmass input parameters particles listparticle a list of particles where each particle is a tuple with its x y z position and its mass returns coord3d a tuple with the coordinates of the center of mass xcm ycm zcm rounded to two decimal places examples centerofmass particle1 5 4 3 4 4 particle5 6 8 7 8 1 particle9 4 10 1 11 6 12 coord3dx6 61 y7 98 z8 69 centerofmass particle1 2 3 4 particle5 6 7 8 particle9 10 11 12 coord3dx6 33 y7 33 z8 33 centerofmass particle1 2 3 4 particle5 6 7 8 particle9 10 11 12 traceback most recent call last valueerror mass of all particles must be greater than 0 centerofmass particle1 2 3 0 particle5 6 7 8 particle9 10 11 12 traceback most recent call last valueerror mass of all particles must be greater than 0 centerofmass traceback most recent call last valueerror no particles provided noqa pyi024 noqa pyi024 input parameters particles list particle a list of particles where each particle is a tuple with it s x y z position and it s mass returns coord3d a tuple with the coordinates of the center of mass xcm ycm zcm rounded to two decimal places examples center_of_mass particle 1 5 4 3 4 4 particle 5 6 8 7 8 1 particle 9 4 10 1 11 6 12 coord3d x 6 61 y 7 98 z 8 69 center_of_mass particle 1 2 3 4 particle 5 6 7 8 particle 9 10 11 12 coord3d x 6 33 y 7 33 z 8 33 center_of_mass particle 1 2 3 4 particle 5 6 7 8 particle 9 10 11 12 traceback most recent call last valueerror mass of all particles must be greater than 0 center_of_mass particle 1 2 3 0 particle 5 6 7 8 particle 9 10 11 12 traceback most recent call last valueerror mass of all particles must be greater than 0 center_of_mass traceback most recent call last valueerror no particles provided
from collections import namedtuple Particle = namedtuple("Particle", "x y z mass") Coord3D = namedtuple("Coord3D", "x y z") def center_of_mass(particles: list[Particle]) -> Coord3D: if not particles: raise ValueError("No particles provided") if any(particle.mass <= 0 for particle in particles): raise ValueError("Mass of all particles must be greater than 0") total_mass = sum(particle.mass for particle in particles) center_of_mass_x = round( sum(particle.x * particle.mass for particle in particles) / total_mass, 2 ) center_of_mass_y = round( sum(particle.y * particle.mass for particle in particles) / total_mass, 2 ) center_of_mass_z = round( sum(particle.z * particle.mass for particle in particles) / total_mass, 2 ) return Coord3D(center_of_mass_x, center_of_mass_y, center_of_mass_z) if __name__ == "__main__": import doctest doctest.testmod()
description centripetal force is the force acting on an object in curvilinear motion directed towards the axis of rotation or centre of curvature the unit of centripetal force is newton the centripetal force is always directed perpendicular to the direction of the objects displacement using newtons second law of motion it is found that the centripetal force of an object moving in a circular path always acts towards the centre of the circle the centripetal force formula is given as the product of mass in kg and tangential velocity in meters per second squared divided by the radius in meters that implies that on doubling the tangential velocity the centripetal force will be quadrupled mathematically it is written as f mvr where f is the centripetal force m is the mass of the object v is the speed or velocity of the object and r is the radius reference https byjus comphysicscentripetalandcentrifugalforce the centripetal force formula is given as mvvr roundcentripetal15 5 30 10 2 1395 0 roundcentripetal10 15 5 2 450 0 roundcentripetal20 50 15 2 3333 33 roundcentripetal12 25 40 25 2 784 0 roundcentripetal50 100 50 2 10000 0 the centripetal force formula is given as m v v r round centripetal 15 5 30 10 2 1395 0 round centripetal 10 15 5 2 450 0 round centripetal 20 50 15 2 3333 33 round centripetal 12 25 40 25 2 784 0 round centripetal 50 100 50 2 10000 0
def centripetal(mass: float, velocity: float, radius: float) -> float: if mass < 0: raise ValueError("The mass of the body cannot be negative") if radius <= 0: raise ValueError("The radius is always a positive non zero integer") return (mass * (velocity) ** 2) / radius if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
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 f k q1 q2 r2 k is coulomb s constant and equals 140 q1 is charge of first body c q2 is charge of second body c r is distance between two charged bodies m reference https en wikipedia orgwikicoulomb27slaw calculate the electrostatic force of attraction or repulsion between two point charges coulombslaw15 5 20 15 12382849136 06 coulombslaw1 15 5 5392531075 38 coulombslaw20 50 15 39944674632 44 coulombslaw5 8 10 3595020716 92 coulombslaw50 100 50 17975103584 6 calculate the electrostatic force of attraction or repulsion between two point charges coulombs_law 15 5 20 15 12382849136 06 coulombs_law 1 15 5 5392531075 38 coulombs_law 20 50 15 39944674632 44 coulombs_law 5 8 10 3595020716 92 coulombs_law 50 100 50 17975103584 6
def coulombs_law(q1: float, q2: float, radius: float) -> float: if radius <= 0: raise ValueError("The radius is always a positive number") return round(((8.9875517923 * 10**9) * q1 * q2) / (radius**2), 2) if __name__ == "__main__": import doctest doctest.testmod()
doppler s effect the doppler effect also doppler shift is the change in the frequency of a wave in relation to an observer who is moving relative to the source of the wave the doppler effect is named after the physicist christian doppler a common example of doppler shift is the change of pitch heard when a vehicle sounding a horn approaches and recedes from an observer the reason for the doppler effect is that when the source of the waves is moving towards the observer each successive wave crest is emitted from a position closer to the observer than the crest of the previous wave therefore each wave takes slightly less time to reach the observer than the previous wave hence the time between the arrivals of successive wave crests at the observer is reduced causing an increase in the frequency similarly if the source of waves is moving away from the observer each wave is emitted from a position farther from the observer than the previous wave so the arrival time between successive waves is increased reducing the frequency if the source of waves is stationary but the observer is moving with respect to the source the transmission velocity of the waves changes ie the rate at which the observer receives waves even if the wavelength and frequency emitted from the source remain constant these results are all summarized by the doppler formula f f0 v v0 v vs where f frequency of the wave f0 frequency of the wave when the source is stationary v velocity of the wave in the medium v0 velocity of the observer positive if the observer is moving towards the source vs velocity of the source positive if the source is moving towards the observer doppler s effect has many applications in physics and engineering such as radar astronomy medical imaging and seismology references https en wikipedia orgwikidopplereffect now we will implement a function that calculates the frequency of a wave as a function of the frequency of the wave when the source is stationary the velocity of the wave in the medium the velocity of the observer and the velocity of the source input parameters orgfreq frequency of the wave when the source is stationary wavevel velocity of the wave in the medium obsvel velocity of the observer ve if the observer is moving towards the source srcvel velocity of the source ve if the source is moving towards the observer returns f frequency of the wave as perceived by the observer docstring tests dopplereffect100 330 10 0 observer moving towards the source 103 03030303030303 dopplereffect100 330 10 0 observer moving away from the source 96 96969696969697 dopplereffect100 330 0 10 source moving towards the observer 103 125 dopplereffect100 330 0 10 source moving away from the observer 97 05882352941177 dopplereffect100 330 10 10 source observer moving towards each other 106 25 dopplereffect100 330 10 10 source and observer moving away 94 11764705882354 dopplereffect100 330 10 330 source moving at same speed as the wave traceback most recent call last zerodivisionerror division by zero implies vsv and observer in front of the source dopplereffect100 330 10 340 source moving faster than the wave traceback most recent call last valueerror nonpositive frequency implies vsv or v0v in the opposite direction dopplereffect100 330 340 10 observer moving faster than the wave traceback most recent call last valueerror nonpositive frequency implies vsv or v0v in the opposite direction input parameters org_freq frequency of the wave when the source is stationary wave_vel velocity of the wave in the medium obs_vel velocity of the observer ve if the observer is moving towards the source src_vel velocity of the source ve if the source is moving towards the observer returns f frequency of the wave as perceived by the observer docstring tests doppler_effect 100 330 10 0 observer moving towards the source 103 03030303030303 doppler_effect 100 330 10 0 observer moving away from the source 96 96969696969697 doppler_effect 100 330 0 10 source moving towards the observer 103 125 doppler_effect 100 330 0 10 source moving away from the observer 97 05882352941177 doppler_effect 100 330 10 10 source observer moving towards each other 106 25 doppler_effect 100 330 10 10 source and observer moving away 94 11764705882354 doppler_effect 100 330 10 330 source moving at same speed as the wave traceback most recent call last zerodivisionerror division by zero implies vs v and observer in front of the source doppler_effect 100 330 10 340 source moving faster than the wave traceback most recent call last valueerror non positive frequency implies vs v or v0 v in the opposite direction doppler_effect 100 330 340 10 observer moving faster than the wave traceback most recent call last valueerror non positive frequency implies vs v or v0 v in the opposite direction
def doppler_effect( org_freq: float, wave_vel: float, obs_vel: float, src_vel: float ) -> float: if wave_vel == src_vel: raise ZeroDivisionError( "Division by zero implies vs=v and observer in front of the source" ) doppler_freq = (org_freq * (wave_vel + obs_vel)) / (wave_vel - src_vel) if doppler_freq <= 0: raise ValueError( "Non-positive frequency implies vs>v or v0>v (in the opposite direction)" ) return doppler_freq if __name__ == "__main__": import doctest doctest.testmod()
title graham s law of effusion description graham s law of effusion states that the rate of effusion of a gas is inversely proportional to the square root of the molar mass of its particles r1r2 sqrtm2m1 r1 rate of effusion for the first gas r2 rate of effusion for the second gas m1 molar mass of the first gas m2 molar mass of the second gas description adapted from https en wikipedia orgwikigraham27slaw input parameters effusionrate1 effustion rate of first gas m2s mm2s etc effusionrate2 effustion rate of second gas m2s mm2s etc molarmass1 molar mass of the first gas gmol kgkmol etc molarmass2 molar mass of the second gas gmol kgkmol etc returns validate2 016 4 002 true validate2 016 4 002 false validate false input parameters molarmass1 molar mass of the first gas gmol kgkmol etc molarmass2 molar mass of the second gas gmol kgkmol etc returns effusionratio2 016 4 002 1 408943 effusionratio2 016 4 002 valueerror input error molar mass values must greater than 0 effusionratio2 016 traceback most recent call last typeerror effusionratio missing 1 required positional argument molarmass2 input parameters effusionrate effustion rate of second gas m2s mm2s etc molarmass1 molar mass of the first gas gmol kgkmol etc molarmass2 molar mass of the second gas gmol kgkmol etc returns firsteffusionrate1 2 016 4 002 1 408943 firsteffusionrate1 2 016 4 002 valueerror input error molar mass and effusion rate values must greater than 0 firsteffusionrate1 traceback most recent call last typeerror firsteffusionrate missing 2 required positional arguments molarmass1 and molarmass2 firsteffusionrate1 2 016 traceback most recent call last typeerror firsteffusionrate missing 1 required positional argument molarmass2 input parameters effusionrate effustion rate of second gas m2s mm2s etc molarmass1 molar mass of the first gas gmol kgkmol etc molarmass2 molar mass of the second gas gmol kgkmol etc returns secondeffusionrate1 2 016 4 002 0 709752 secondeffusionrate1 2 016 4 002 valueerror input error molar mass and effusion rate values must greater than 0 secondeffusionrate1 traceback most recent call last typeerror secondeffusionrate missing 2 required positional arguments molarmass1 and molarmass2 secondeffusionrate1 2 016 traceback most recent call last typeerror secondeffusionrate missing 1 required positional argument molarmass2 input parameters molarmass molar mass of the first gas gmol kgkmol etc effusionrate1 effustion rate of first gas m2s mm2s etc effusionrate2 effustion rate of second gas m2s mm2s etc returns firstmolarmass2 1 408943 0 709752 0 507524 firstmolarmass1 2 016 4 002 valueerror input error molar mass and effusion rate values must greater than 0 firstmolarmass1 traceback most recent call last typeerror firstmolarmass missing 2 required positional arguments effusionrate1 and effusionrate2 firstmolarmass1 2 016 traceback most recent call last typeerror firstmolarmass missing 1 required positional argument effusionrate2 input parameters molarmass molar mass of the first gas gmol kgkmol etc effusionrate1 effustion rate of first gas m2s mm2s etc effusionrate2 effustion rate of second gas m2s mm2s etc returns secondmolarmass2 1 408943 0 709752 1 970351 secondmolarmass2 1 408943 0 709752 valueerror input error molar mass and effusion rate values must greater than 0 secondmolarmass1 traceback most recent call last typeerror secondmolarmass missing 2 required positional arguments effusionrate1 and effusionrate2 secondmolarmass1 2 016 traceback most recent call last typeerror secondmolarmass missing 1 required positional argument effusionrate2 input parameters effusion_rate_1 effustion rate of first gas m 2 s mm 2 s etc effusion_rate_2 effustion rate of second gas m 2 s mm 2 s etc molar_mass_1 molar mass of the first gas g mol kg kmol etc molar_mass_2 molar mass of the second gas g mol kg kmol etc returns validate 2 016 4 002 true validate 2 016 4 002 false validate false input parameters molar_mass_1 molar mass of the first gas g mol kg kmol etc molar_mass_2 molar mass of the second gas g mol kg kmol etc returns effusion_ratio 2 016 4 002 1 408943 effusion_ratio 2 016 4 002 valueerror input error molar mass values must greater than 0 effusion_ratio 2 016 traceback most recent call last typeerror effusion_ratio missing 1 required positional argument molar_mass_2 input parameters effusion_rate effustion rate of second gas m 2 s mm 2 s etc molar_mass_1 molar mass of the first gas g mol kg kmol etc molar_mass_2 molar mass of the second gas g mol kg kmol etc returns first_effusion_rate 1 2 016 4 002 1 408943 first_effusion_rate 1 2 016 4 002 valueerror input error molar mass and effusion rate values must greater than 0 first_effusion_rate 1 traceback most recent call last typeerror first_effusion_rate missing 2 required positional arguments molar_mass_1 and molar_mass_2 first_effusion_rate 1 2 016 traceback most recent call last typeerror first_effusion_rate missing 1 required positional argument molar_mass_2 input parameters effusion_rate effustion rate of second gas m 2 s mm 2 s etc molar_mass_1 molar mass of the first gas g mol kg kmol etc molar_mass_2 molar mass of the second gas g mol kg kmol etc returns second_effusion_rate 1 2 016 4 002 0 709752 second_effusion_rate 1 2 016 4 002 valueerror input error molar mass and effusion rate values must greater than 0 second_effusion_rate 1 traceback most recent call last typeerror second_effusion_rate missing 2 required positional arguments molar_mass_1 and molar_mass_2 second_effusion_rate 1 2 016 traceback most recent call last typeerror second_effusion_rate missing 1 required positional argument molar_mass_2 input parameters molar_mass molar mass of the first gas g mol kg kmol etc effusion_rate_1 effustion rate of first gas m 2 s mm 2 s etc effusion_rate_2 effustion rate of second gas m 2 s mm 2 s etc returns first_molar_mass 2 1 408943 0 709752 0 507524 first_molar_mass 1 2 016 4 002 valueerror input error molar mass and effusion rate values must greater than 0 first_molar_mass 1 traceback most recent call last typeerror first_molar_mass missing 2 required positional arguments effusion_rate_1 and effusion_rate_2 first_molar_mass 1 2 016 traceback most recent call last typeerror first_molar_mass missing 1 required positional argument effusion_rate_2 input parameters molar_mass molar mass of the first gas g mol kg kmol etc effusion_rate_1 effustion rate of first gas m 2 s mm 2 s etc effusion_rate_2 effustion rate of second gas m 2 s mm 2 s etc returns second_molar_mass 2 1 408943 0 709752 1 970351 second_molar_mass 2 1 408943 0 709752 valueerror input error molar mass and effusion rate values must greater than 0 second_molar_mass 1 traceback most recent call last typeerror second_molar_mass missing 2 required positional arguments effusion_rate_1 and effusion_rate_2 second_molar_mass 1 2 016 traceback most recent call last typeerror second_molar_mass missing 1 required positional argument effusion_rate_2
from math import pow, sqrt def validate(*values: float) -> bool: result = len(values) > 0 and all(value > 0.0 for value in values) return result def effusion_ratio(molar_mass_1: float, molar_mass_2: float) -> float | ValueError: return ( round(sqrt(molar_mass_2 / molar_mass_1), 6) if validate(molar_mass_1, molar_mass_2) else ValueError("Input Error: Molar mass values must greater than 0.") ) def first_effusion_rate( effusion_rate: float, molar_mass_1: float, molar_mass_2: float ) -> float | ValueError: return ( round(effusion_rate * sqrt(molar_mass_2 / molar_mass_1), 6) if validate(effusion_rate, molar_mass_1, molar_mass_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def second_effusion_rate( effusion_rate: float, molar_mass_1: float, molar_mass_2: float ) -> float | ValueError: return ( round(effusion_rate / sqrt(molar_mass_2 / molar_mass_1), 6) if validate(effusion_rate, molar_mass_1, molar_mass_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def first_molar_mass( molar_mass: float, effusion_rate_1: float, effusion_rate_2: float ) -> float | ValueError: return ( round(molar_mass / pow(effusion_rate_1 / effusion_rate_2, 2), 6) if validate(molar_mass, effusion_rate_1, effusion_rate_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def second_molar_mass( molar_mass: float, effusion_rate_1: float, effusion_rate_2: float ) -> float | ValueError: return ( round(pow(effusion_rate_1 / effusion_rate_2, 2) / molar_mass, 6) if validate(molar_mass, effusion_rate_1, effusion_rate_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) )
horizontal projectile motion problem in physics this algorithm solves a specific problem in which the motion starts from the ground as can be seen below v 0 ground ground for more info https en wikipedia orgwikiprojectilemotion importing packages acceleration constant on earth unit ms2 check that the arguments are valid ensure valid instance ensure valid angle ensure valid velocity returns the horizontal distance that the object cover formula v02 sin2 alpha g v0 initial velocity alpha angle horizontaldistance30 45 91 77 horizontaldistance100 78 414 76 horizontaldistance1 20 traceback most recent call last valueerror invalid velocity should be a positive number horizontaldistance30 20 traceback most recent call last valueerror invalid angle range is 190 degrees returns the maximum height that the object reach formula v02 sin2alpha 2g v0 initial velocity alpha angle maxheight30 45 22 94 maxheight100 78 487 82 maxheighta 20 traceback most recent call last typeerror invalid velocity should be a positive number horizontaldistance30 b traceback most recent call last typeerror invalid angle range is 190 degrees returns total time of the motion formula 2 v0 sinalpha g v0 initial velocity alpha angle totaltime30 45 4 33 totaltime100 78 19 95 totaltime10 40 traceback most recent call last valueerror invalid velocity should be a positive number totaltime30 b traceback most recent call last typeerror invalid angle range is 190 degrees testmotion get input from user get input from user print results importing packages acceleration constant on earth unit m s 2 check that the arguments are valid ensure valid instance ensure valid angle ensure valid velocity returns the horizontal distance that the object cover formula v_0 2 sin 2 alpha g v_0 initial velocity alpha angle horizontal_distance 30 45 91 77 horizontal_distance 100 78 414 76 horizontal_distance 1 20 traceback most recent call last valueerror invalid velocity should be a positive number horizontal_distance 30 20 traceback most recent call last valueerror invalid angle range is 1 90 degrees returns the maximum height that the object reach formula v_0 2 sin 2 alpha 2g v_0 initial velocity alpha angle max_height 30 45 22 94 max_height 100 78 487 82 max_height a 20 traceback most recent call last typeerror invalid velocity should be a positive number horizontal_distance 30 b traceback most recent call last typeerror invalid angle range is 1 90 degrees returns total time of the motion formula 2 v_0 sin alpha g v_0 initial velocity alpha angle total_time 30 45 4 33 total_time 100 78 19 95 total_time 10 40 traceback most recent call last valueerror invalid velocity should be a positive number total_time 30 b traceback most recent call last typeerror invalid angle range is 1 90 degrees test_motion get input from user get input from user print results
from math import radians as angle_to_radians from math import sin g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be a positive number.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Range is 1-90 degrees.") if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.") def horizontal_distance(init_velocity: float, angle: float) -> float: check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74 if __name__ == "__main__": from doctest import testmod testmod() init_vel = float(input("Initial Velocity: ").strip()) angle = float(input("angle: ").strip()) print() print("Results: ") print(f"Horizontal Distance: {horizontal_distance(init_vel, angle)!s} [m]") print(f"Maximum Height: {max_height(init_vel, angle)!s} [m]") print(f"Total Time: {total_time(init_vel, angle)!s} [s]")
title calculating the hubble parameter description the hubble parameter h is the universe expansion rate in any time in cosmology is customary to use the redshift redshift in place of time becausethe redshift is directily mensure in the light of galaxies moving away from us so the general relation that we obtain is h hubbleconstantradiationdensityredshift14 matterdensityredshift13 curvatureredshift12 darkenergy12 where radiationdensity matterdensity darkenergy are the relativity the percentage energy densities that exist in the universe today here matterdensity is the sum of the barion density and the dark matter curvature is the curvature parameter and can be written in term of the densities by the completeness curvature 1 matterdensity radiationdensity darkenergy source https www sciencedirect comtopicsmathematicshubbleparameter input parameters hubbleconstant hubble constante is the expansion rate today usually given in kmsmpc radiationdensity relative radiation density today matterdensity relative mass density today darkenergy relative dark energy density today redshift the light redshift returns result hubble parameter in and the unit kmsmpc the unit can be changed if you want just need to change the unit of the hubble constant hubbleparameterhubbleconstant68 3 radiationdensity1e4 matterdensity0 3 darkenergy0 7 redshift1 traceback most recent call last valueerror all input parameters must be positive hubbleparameterhubbleconstant68 3 radiationdensity1e4 matterdensity 1 2 darkenergy0 7 redshift1 traceback most recent call last valueerror relative densities cannot be greater than one hubbleparameterhubbleconstant68 3 radiationdensity1e4 matterdensity 0 3 darkenergy0 7 redshift0 68 3 run doctest demo lcdm approximation input parameters hubble_constant hubble constante is the expansion rate today usually given in km s mpc radiation_density relative radiation density today matter_density relative mass density today dark_energy relative dark energy density today redshift the light redshift returns result hubble parameter in and the unit km s mpc the unit can be changed if you want just need to change the unit of the hubble constant hubble_parameter hubble_constant 68 3 radiation_density 1e 4 matter_density 0 3 dark_energy 0 7 redshift 1 traceback most recent call last valueerror all input parameters must be positive hubble_parameter hubble_constant 68 3 radiation_density 1e 4 matter_density 1 2 dark_energy 0 7 redshift 1 traceback most recent call last valueerror relative densities cannot be greater than one hubble_parameter hubble_constant 68 3 radiation_density 1e 4 matter_density 0 3 dark_energy 0 7 redshift 0 68 3 run doctest demo lcdm approximation
def hubble_parameter( hubble_constant: float, radiation_density: float, matter_density: float, dark_energy: float, redshift: float, ) -> float: parameters = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters): raise ValueError("All input parameters must be positive") if any(p > 1 for p in parameters[1:4]): raise ValueError("Relative densities cannot be greater than one") else: curvature = 1 - (matter_density + radiation_density + dark_energy) e_2 = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) hubble = hubble_constant * e_2 ** (1 / 2) return hubble if __name__ == "__main__": import doctest doctest.testmod() matter_density = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
the ideal gas law also called the general gas equation is the equation of state of a hypothetical ideal gas it is a good approximation of the behavior of many gases under many conditions although it has several limitations it was first stated by benot paul mile clapeyron in 1834 as a combination of the empirical boyle s law charles s law avogadro s law and gaylussac s law 1 the ideal gas law is often written in an empirical form pv nrt p pressure pa v volume m3 n amount of substance mol r universal gas constant t absolute temperature kelvin description adapted from https en wikipedia orgwikiidealgaslaw pressureofgassystem2 100 5 332 57848 pressureofgassystem0 5 273 0 004 283731 01575 pressureofgassystem3 0 46 23 5 traceback most recent call last valueerror invalid inputs enter positive value volumeofgassystem2 100 5 332 57848 volumeofgassystem0 5 273 0 004 283731 01575 volumeofgassystem3 0 46 23 5 traceback most recent call last valueerror invalid inputs enter positive value temperatureofgassystem2 100 5 30 068090996146232 temperatureofgassystem11 5009 1000 54767 66101807144 temperatureofgassystem3 0 46 23 5 traceback most recent call last valueerror invalid inputs enter positive value molesofgassystem100 5 10 0 06013618199229246 molesofgassystem110 5009 1000 5476 766101807144 molesofgassystem3 0 46 23 5 traceback most recent call last valueerror invalid inputs enter positive value unit j mol 1 k 1 pressure_of_gas_system 2 100 5 332 57848 pressure_of_gas_system 0 5 273 0 004 283731 01575 pressure_of_gas_system 3 0 46 23 5 traceback most recent call last valueerror invalid inputs enter positive value volume_of_gas_system 2 100 5 332 57848 volume_of_gas_system 0 5 273 0 004 283731 01575 volume_of_gas_system 3 0 46 23 5 traceback most recent call last valueerror invalid inputs enter positive value temperature_of_gas_system 2 100 5 30 068090996146232 temperature_of_gas_system 11 5009 1000 54767 66101807144 temperature_of_gas_system 3 0 46 23 5 traceback most recent call last valueerror invalid inputs enter positive value moles_of_gas_system 100 5 10 0 06013618199229246 moles_of_gas_system 110 5009 1000 5476 766101807144 moles_of_gas_system 3 0 46 23 5 traceback most recent call last valueerror invalid inputs enter positive value
UNIVERSAL_GAS_CONSTANT = 8.314462 def pressure_of_gas_system(moles: float, kelvin: float, volume: float) -> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def volume_of_gas_system(moles: float, kelvin: float, pressure: float) -> float: if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure def temperature_of_gas_system(moles: float, volume: float, pressure: float) -> float: if moles < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return pressure * volume / (moles * UNIVERSAL_GAS_CONSTANT) def moles_of_gas_system(kelvin: float, volume: float, pressure: float) -> float: if kelvin < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return pressure * volume / (kelvin * UNIVERSAL_GAS_CONSTANT) if __name__ == "__main__": from doctest import testmod testmod()
checks if a system of forces is in static equilibrium resolves force along rectangular components force angle forcex forcey import math force polarforce10 45 math iscloseforce0 7 071067811865477 true math iscloseforce1 7 0710678118654755 true force polarforce10 3 14 radianmodetrue math iscloseforce0 9 999987317275396 true math iscloseforce1 0 01592652916486828 true check if a system is in equilibrium it takes two numpy array objects forces force1x force1y force2x force2y location x1 y1 x2 y2 force array1 1 1 2 location array1 0 10 0 instaticequilibriumforce location false summation of moments is zero test to check if it works problem 1 in imagedata2dproblems jpg problem in imagedata2dproblems1 jpg resolves force along rectangular components force angle force_x force_y import math force polar_force 10 45 math isclose force 0 7 071067811865477 true math isclose force 1 7 0710678118654755 true force polar_force 10 3 14 radian_mode true math isclose force 0 9 999987317275396 true math isclose force 1 0 01592652916486828 true check if a system is in equilibrium it takes two numpy array objects forces force1_x force1_y force2_x force2_y location x1 y1 x2 y2 force array 1 1 1 2 location array 1 0 10 0 in_static_equilibrium force location false summation of moments is zero test to check if it works problem 1 in image_data 2d_problems jpg problem in image_data 2d_problems_1 jpg
from __future__ import annotations from numpy import array, cos, cross, float64, radians, sin from numpy.typing import NDArray def polar_force( magnitude: float, angle: float, radian_mode: bool = False ) -> list[float]: if radian_mode: return [magnitude * cos(angle), magnitude * sin(angle)] return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))] def in_static_equilibrium( forces: NDArray[float64], location: NDArray[float64], eps: float = 10**-1 ) -> bool: moments: NDArray[float64] = cross(location, forces) sum_moments: float = sum(moments) return abs(sum_moments) < eps if __name__ == "__main__": forces = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) location: NDArray[float64] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) forces = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) location = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) location = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
find the kinetic energy of an object given its mass and velocity description in physics the kinetic energy of an object is the energy that it possesses due to its motion it is defined as the work needed to accelerate a body of a given mass from rest to its stated velocity having gained this energy during its acceleration the body maintains this kinetic energy unless its speed changes the same amount of work is done by the body when decelerating from its current speed to a state of rest formally a kinetic energy is any term in a system s lagrangian which includes a derivative with respect to time in classical mechanics the kinetic energy of a nonrotating object of mass m traveling at a speed v is mv in relativistic mechanics this is a good approximation only when v is much less than the speed of light the standard unit of kinetic energy is the joule while the english unit of kinetic energy is the footpound reference https en m wikipedia orgwikikineticenergy calculate kinetic energy the kinetic energy of a nonrotating object of mass m traveling at a speed v is mv kineticenergy10 10 500 0 kineticenergy0 10 0 0 kineticenergy10 0 0 0 kineticenergy20 20 4000 0 kineticenergy0 0 0 0 kineticenergy2 2 4 0 kineticenergy100 100 500000 0 calculate kinetic energy the kinetic energy of a non rotating object of mass m traveling at a speed v is ½mv² kinetic_energy 10 10 500 0 kinetic_energy 0 10 0 0 kinetic_energy 10 0 0 0 kinetic_energy 20 20 4000 0 kinetic_energy 0 0 0 0 kinetic_energy 2 2 4 0 kinetic_energy 100 100 500000 0
def kinetic_energy(mass: float, velocity: float) -> float: if mass < 0: raise ValueError("The mass of a body cannot be negative") return 0.5 * mass * abs(velocity) * abs(velocity) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
this module has functions which calculate focal length of lens distance of image from the lens and distance of object from the lens the above is calculated using the lens formula in optics the relationship between the distance of the image v the distance of the object u and the focal length f of the lens is given by the formula known as the lens formula the lens formula is applicable for convex as well as concave lenses the formula is given as follows 1f 1v 1u where f focal length of the lens in meters v distance of the image from the lens in meters u distance of the object from the lens in meters to make our calculations easy few assumptions are made while deriving the formula which are important to keep in mind before solving this equation the assumptions are as follows 1 the object o is a point object lying somewhere on the principle axis 2 the lens is thin 3 the aperture of the lens taken must be small 4 the angles of incidence and angle of refraction should be small sign convention is a set of rules to set signs for image distance object distance focal length etc for mathematical analysis of image formation according to it 1 object is always placed to the left of lens 2 all distances are measured from the optical centre of the mirror 3 distances measured in the direction of the incident ray are positive and the distances measured in the direction opposite to that of the incident rays are negative 4 distances measured along yaxis above the principal axis are positive and that measured along yaxis below the principal axis are negative note sign convention can be reversed and will still give the correct results reference for sign convention https www toppr comaskcontentconceptsignconventionforlenses210246 reference for assumptions https testbook comphysicsderivationoflensmakerformula doctests from math import isclose isclosefocallengthoflens10 4 6 666666666666667 true from math import isclose isclosefocallengthoflens2 7 5 8 5 0516129032258075 true focallengthoflens0 20 doctest normalizewhitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention doctests from math import isclose iscloseobjectdistance10 40 13 333333333333332 true from math import isclose iscloseobjectdistance6 2 1 5 1 9787234042553192 true objectdistance0 20 doctest normalizewhitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention doctests from math import isclose iscloseimagedistance50 40 22 22222222222222 true from math import isclose iscloseimagedistance5 3 7 9 3 1719696969696973 true objectdistance0 20 doctest normalizewhitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention doctests from math import isclose isclose focal_length_of_lens 10 4 6 666666666666667 true from math import isclose isclose focal_length_of_lens 2 7 5 8 5 0516129032258075 true focal_length_of_lens 0 20 doctest normalize_whitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention doctests from math import isclose isclose object_distance 10 40 13 333333333333332 true from math import isclose isclose object_distance 6 2 1 5 1 9787234042553192 true object_distance 0 20 doctest normalize_whitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention doctests from math import isclose isclose image_distance 50 40 22 22222222222222 true from math import isclose isclose image_distance 5 3 7 9 3 1719696969696973 true object_distance 0 20 doctest normalize_whitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention
def focal_length_of_lens( object_distance_from_lens: float, image_distance_from_lens: float ) -> float: if object_distance_from_lens == 0 or image_distance_from_lens == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) focal_length = 1 / ( (1 / image_distance_from_lens) - (1 / object_distance_from_lens) ) return focal_length def object_distance( focal_length_of_lens: float, image_distance_from_lens: float ) -> float: if image_distance_from_lens == 0 or focal_length_of_lens == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) object_distance = 1 / ((1 / image_distance_from_lens) - (1 / focal_length_of_lens)) return object_distance def image_distance( focal_length_of_lens: float, object_distance_from_lens: float ) -> float: if object_distance_from_lens == 0 or focal_length_of_lens == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) image_distance = 1 / ((1 / object_distance_from_lens) + (1 / focal_length_of_lens)) return image_distance
lorentz transformations describe the transition between two inertial reference frames f and f each of which is moving in some direction with respect to the other this code only calculates lorentz transformations for movement in the x direction with no spatial rotation i e a lorentz boost in the x direction the lorentz transformations are calculated here as linear transformations of fourvectors ct x y z described by minkowski space note that t time is multiplied by c the speed of light in the first entry of each fourvector thus if x ct x y z and x ct x y z are the fourvectors for two inertial reference frames and x moves in the x direction with velocity v with respect to x then the lorentz transformation from x to x is x bx where 0 0 b 0 0 0 0 1 0 0 0 0 1 is the matrix describing the lorentz boost between x and x 1 1 vc is the lorentz factor and vc is the velocity as a fraction of c reference https en wikipedia orgwikilorentztransformation coefficient speed of light ms symbols vehicle s speed divided by speed of light no units calculates vc the given velocity as a fraction of c betac 1 0 beta199792458 0 666435904801848 beta1e5 0 00033356409519815205 beta0 2 traceback most recent call last valueerror speed must be greater than or equal to 1 usually the speed should be much higher than 1 c order of magnitude calculate the lorentz factor 1 1 vc for a given velocity gamma4 1 0000000000000002 gamma1e5 1 0000000556325075 gamma3e7 1 005044845777813 gamma2 8e8 2 7985595722318277 gamma299792451 4627 49902669495 gamma0 3 traceback most recent call last valueerror speed must be greater than or equal to 1 gamma2 c traceback most recent call last valueerror speed must not exceed light speed 299 792 458 ms calculate the lorentz transformation matrix for movement in the x direction 0 0 0 0 0 0 1 0 0 0 0 1 where is the lorentz factor and is the velocity as a fraction of c transformationmatrix29979245 array 1 00503781 0 10050378 0 0 0 10050378 1 00503781 0 0 0 0 1 0 0 0 0 1 transformationmatrix19979245 2 array 1 00222811 0 06679208 0 0 0 06679208 1 00222811 0 0 0 0 1 0 0 0 0 1 transformationmatrix1 array 1 00000000e00 3 33564095e09 0 00000000e00 0 00000000e00 3 33564095e09 1 00000000e00 0 00000000e00 0 00000000e00 0 00000000e00 0 00000000e00 1 00000000e00 0 00000000e00 0 00000000e00 0 00000000e00 0 00000000e00 1 00000000e00 transformationmatrix0 traceback most recent call last valueerror speed must be greater than or equal to 1 transformationmatrixc 1 5 traceback most recent call last valueerror speed must not exceed light speed 299 792 458 ms calculate a lorentz transformation for movement in the x direction given a velocity and a fourvector for an inertial reference frame if no fourvector is given then calculate the transformation symbolically with variables transform29979245 np array1 2 3 4 array 3 01302757e08 3 01302729e07 3 00000000e00 4 00000000e00 transform29979245 array1 00503781498831ct 0 100503778816875x 0 100503778816875ct 1 00503781498831x 1 0y 1 0z dtypeobject transform19879210 2 array1 0022057787097ct 0 066456172618675x 0 066456172618675ct 1 0022057787097x 1 0y 1 0z dtypeobject transform299792459 np array1 1 1 1 traceback most recent call last valueerror speed must not exceed light speed 299 792 458 ms transform1 np array1 1 1 1 traceback most recent call last valueerror speed must be greater than or equal to 1 ensure event is not empty example of symbolic vector substitute symbols with numerical values coefficient speed of light m s symbols vehicle s speed divided by speed of light no units calculates β v c the given velocity as a fraction of c beta c 1 0 beta 199792458 0 666435904801848 beta 1e5 0 00033356409519815205 beta 0 2 traceback most recent call last valueerror speed must be greater than or equal to 1 usually the speed should be much higher than 1 c order of magnitude calculate the lorentz factor γ 1 1 v² c² for a given velocity gamma 4 1 0000000000000002 gamma 1e5 1 0000000556325075 gamma 3e7 1 005044845777813 gamma 2 8e8 2 7985595722318277 gamma 299792451 4627 49902669495 gamma 0 3 traceback most recent call last valueerror speed must be greater than or equal to 1 gamma 2 c traceback most recent call last valueerror speed must not exceed light speed 299 792 458 m s calculate the lorentz transformation matrix for movement in the x direction γ γβ 0 0 γβ γ 0 0 0 0 1 0 0 0 0 1 where γ is the lorentz factor and β is the velocity as a fraction of c transformation_matrix 29979245 array 1 00503781 0 10050378 0 0 0 10050378 1 00503781 0 0 0 0 1 0 0 0 0 1 transformation_matrix 19979245 2 array 1 00222811 0 06679208 0 0 0 06679208 1 00222811 0 0 0 0 1 0 0 0 0 1 transformation_matrix 1 array 1 00000000e 00 3 33564095e 09 0 00000000e 00 0 00000000e 00 3 33564095e 09 1 00000000e 00 0 00000000e 00 0 00000000e 00 0 00000000e 00 0 00000000e 00 1 00000000e 00 0 00000000e 00 0 00000000e 00 0 00000000e 00 0 00000000e 00 1 00000000e 00 transformation_matrix 0 traceback most recent call last valueerror speed must be greater than or equal to 1 transformation_matrix c 1 5 traceback most recent call last valueerror speed must not exceed light speed 299 792 458 m s calculate a lorentz transformation for movement in the x direction given a velocity and a four vector for an inertial reference frame if no four vector is given then calculate the transformation symbolically with variables transform 29979245 np array 1 2 3 4 array 3 01302757e 08 3 01302729e 07 3 00000000e 00 4 00000000e 00 transform 29979245 array 1 00503781498831 ct 0 100503778816875 x 0 100503778816875 ct 1 00503781498831 x 1 0 y 1 0 z dtype object transform 19879210 2 array 1 0022057787097 ct 0 066456172618675 x 0 066456172618675 ct 1 0022057787097 x 1 0 y 1 0 z dtype object transform 299792459 np array 1 1 1 1 traceback most recent call last valueerror speed must not exceed light speed 299 792 458 m s transform 1 np array 1 1 1 1 traceback most recent call last valueerror speed must be greater than or equal to 1 ensure event is not empty symbolic four vector x0 is ct speed of light time example of symbolic vector substitute symbols with numerical values
from math import sqrt import numpy as np from sympy import symbols c = 299792458 ct, x, y, z = symbols("ct x y z") def beta(velocity: float) -> float: if velocity > c: raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!") elif velocity < 1: raise ValueError("Speed must be greater than or equal to 1!") return velocity / c def gamma(velocity: float) -> float: return 1 / sqrt(1 - beta(velocity) ** 2) def transformation_matrix(velocity: float) -> np.ndarray: return np.array( [ [gamma(velocity), -gamma(velocity) * beta(velocity), 0, 0], [-gamma(velocity) * beta(velocity), gamma(velocity), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray: if event is None: event = np.array([ct, x, y, z]) else: event[0] *= c return transformation_matrix(velocity) @ event if __name__ == "__main__": import doctest doctest.testmod() four_vector = transform(29979245) print("Example of four vector: ") print(f"ct' = {four_vector[0]}") print(f"x' = {four_vector[1]}") print(f"y' = {four_vector[2]}") print(f"z' = {four_vector[3]}") sub_dict = {ct: c, x: 1, y: 1, z: 1} numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)] print(f"\n{numerical_vector}")
finding the intensity of light transmitted through a polariser using malus law and by taking initial intensity and angle between polariser and axis as input description malus s law which is named after tiennelouis malus says that when a perfect polarizer is placed in a polarized beam of light the irradiance i of the light that passes through is given by ii cos where i is the initial intensity and is the angle between the light s initial polarization direction and the axis of the polarizer a beam of unpolarized light can be thought of as containing a uniform mixture of linear polarizations at all possible angles since the average value of cos is 12 the transmission coefficient becomes ii 12 in practice some light is lost in the polarizer and the actual transmission will be somewhat lower than this around 38 for polaroidtype polarizers but considerably higher 49 9 for some birefringent prism types if two polarizers are placed one after another the second polarizer is generally called an analyzer the mutual angle between their polarizing axes gives the value of in malus s law if the two axes are orthogonal the polarizers are crossed and in theory no light is transmitted though again practically speaking no polarizer is perfect and the transmission is not exactly zero for example crossed polaroid sheets appear slightly blue in colour because their extinction ratio is better in the red if a transparent object is placed between the crossed polarizers any polarization effects present in the sample such as birefringence will be shown as an increase in transmission this effect is used in polarimetry to measure the optical activity of a sample real polarizers are also not perfect blockers of the polarization orthogonal to their polarization axis the ratio of the transmission of the unwanted component to the wanted component is called the extinction ratio and varies from around 1 500 for polaroid to about 1 106 for glantaylor prism polarizers reference https en wikipedia orgwikipolarizermalus slawandotherproperties roundmaluslaw10 45 2 5 0 roundmaluslaw100 60 2 25 0 roundmaluslaw50 150 2 37 5 roundmaluslaw75 270 2 0 0 roundmaluslaw10 900 2 traceback most recent call last valueerror in malus law the angle is in the range 0360 degrees roundmaluslaw10 900 2 traceback most recent call last valueerror in malus law the angle is in the range 0360 degrees roundmaluslaw100 900 2 traceback most recent call last valueerror the value of intensity cannot be negative roundmaluslaw100 180 2 100 0 roundmaluslaw100 360 2 100 0 handling of negative values of initial intensity handling of values out of allowed range finding the intensity of light transmitted through a polariser using malus law and by taking initial intensity and angle between polariser and axis as input description malus s law which is named after étienne louis malus says that when a perfect polarizer is placed in a polarized beam of light the irradiance i of the light that passes through is given by i i cos²θ where i is the initial intensity and θ is the angle between the light s initial polarization direction and the axis of the polarizer a beam of unpolarized light can be thought of as containing a uniform mixture of linear polarizations at all possible angles since the average value of cos²θ is 1 2 the transmission coefficient becomes i i 1 2 in practice some light is lost in the polarizer and the actual transmission will be somewhat lower than this around 38 for polaroid type polarizers but considerably higher 49 9 for some birefringent prism types if two polarizers are placed one after another the second polarizer is generally called an analyzer the mutual angle between their polarizing axes gives the value of θ in malus s law if the two axes are orthogonal the polarizers are crossed and in theory no light is transmitted though again practically speaking no polarizer is perfect and the transmission is not exactly zero for example crossed polaroid sheets appear slightly blue in colour because their extinction ratio is better in the red if a transparent object is placed between the crossed polarizers any polarization effects present in the sample such as birefringence will be shown as an increase in transmission this effect is used in polarimetry to measure the optical activity of a sample real polarizers are also not perfect blockers of the polarization orthogonal to their polarization axis the ratio of the transmission of the unwanted component to the wanted component is called the extinction ratio and varies from around 1 500 for polaroid to about 1 106 for glan taylor prism polarizers reference https en wikipedia org wiki polarizer malus s_law_and_other_properties round malus_law 10 45 2 5 0 round malus_law 100 60 2 25 0 round malus_law 50 150 2 37 5 round malus_law 75 270 2 0 0 round malus_law 10 900 2 traceback most recent call last valueerror in malus law the angle is in the range 0 360 degrees round malus_law 10 900 2 traceback most recent call last valueerror in malus law the angle is in the range 0 360 degrees round malus_law 100 900 2 traceback most recent call last valueerror the value of intensity cannot be negative round malus_law 100 180 2 100 0 round malus_law 100 360 2 100 0 handling of negative values of initial intensity handling of values out of allowed range
import math def malus_law(initial_intensity: float, angle: float) -> float: if initial_intensity < 0: raise ValueError("The value of intensity cannot be negative") if angle < 0 or angle > 360: raise ValueError("In Malus Law, the angle is in the range 0-360 degrees") return initial_intensity * (math.cos(math.radians(angle)) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name="malus_law")
title finding the energy equivalence of mass and mass equivalence of energy by einstein s equation description einstein s massenergy equivalence is a pivotal concept in theoretical physics it asserts that energy e and mass m are directly related by the speed of light in vacuum c squared as described in the equation e mc this means that mass and energy are interchangeable a mass increase corresponds to an energy increase and vice versa this principle has profound implications in nuclear reactions explaining the release of immense energy from minuscule changes in atomic nuclei equations e mc and m ec where m is mass e is energy c is speed of light in vacuum reference https en wikipedia orgwikimasse28093energyequivalence calculates the energy equivalence of the mass using e mc in si units j from mass in kg mass float mass of body usage example energyfrommass124 56 1 11948945063458e19 energyfrommass320 2 8760165719578165e19 energyfrommass0 0 0 energyfrommass967 9 traceback most recent call last valueerror mass can t be negative calculates the mass equivalence of the energy using m ec in si units kg from energy in j energy float mass of body usage example massfromenergy124 56 1 3859169098203872e15 massfromenergy320 3 560480179371579e15 massfromenergy0 0 0 massfromenergy967 9 traceback most recent call last valueerror energy can t be negative speed of light in vacuum 299792458 m s calculates the energy equivalence of the mass using e mc² in si units j from mass in kg mass float mass of body usage example energy_from_mass 124 56 1 11948945063458e 19 energy_from_mass 320 2 8760165719578165e 19 energy_from_mass 0 0 0 energy_from_mass 967 9 traceback most recent call last valueerror mass can t be negative calculates the mass equivalence of the energy using m e c² in si units kg from energy in j energy float mass of body usage example mass_from_energy 124 56 1 3859169098203872e 15 mass_from_energy 320 3 560480179371579e 15 mass_from_energy 0 0 0 mass_from_energy 967 9 traceback most recent call last valueerror energy can t be negative
from scipy.constants import c def energy_from_mass(mass: float) -> float: if mass < 0: raise ValueError("Mass can't be negative.") return mass * c**2 def mass_from_energy(energy: float) -> float: if energy < 0: raise ValueError("Energy can't be negative.") return energy / c**2 if __name__ == "__main__": import doctest doctest.testmod()
this module contains the functions to calculate the focal length object distance and image distance of a mirror the mirror formula is an equation that relates the object distance u image distance v and focal length f of a spherical mirror it is commonly used in optics to determine the position and characteristics of an image formed by a mirror it is expressed using the formulae 1f 1v 1u where f focal length of the spherical mirror metre v image distance from the mirror metre u object distance from the mirror metre the signs of the distances are taken with respect to the sign convention the sign convention is as follows 1 object is always placed to the left of mirror 2 distances measured in the direction of the incident ray are positive and the distances measured in the direction opposite to that of the incident rays are negative 3 all distances are measured from the pole of the mirror there are a few assumptions that are made while using the mirror formulae they are as follows 1 thin mirror the mirror is assumed to be thin meaning its thickness is negligible compared to its radius of curvature this assumption allows us to treat the mirror as a twodimensional surface 2 spherical mirror the mirror is assumed to have a spherical shape while this assumption may not hold exactly for all mirrors it is a reasonable approximation for most practical purposes 3 small angles the angles involved in the derivation are assumed to be small this assumption allows us to use the smallangle approximation where the tangent of a small angle is approximately equal to the angle itself it simplifies the calculations and makes the derivation more manageable 4 paraxial rays the mirror formula is derived using paraxial rays which are rays that are close to the principal axis and make small angles with it this assumption ensures that the rays are close enough to the principal axis making the calculations more accurate 5 reflection and refraction laws the derivation assumes that the laws of reflection and refraction hold these laws state that the angle of incidence is equal to the angle of reflection for reflection and the incident and refracted rays lie in the same plane and obey snell s law for refraction description and assumptions adapted from https www collegesearch inarticlesmirrorformuladerivation sign convention adapted from https www toppr comaskcontentconceptsignconventionformirrors210189 from math import isclose isclosefocallength10 20 6 66666666666666 true from math import isclose isclosefocallength9 5 6 7 3 929012346 true focallength0 20 doctest normalizewhitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention from math import isclose iscloseobjectdistance30 20 60 0 true from math import isclose iscloseobjectdistance10 5 11 7 102 375 true objectdistance90 0 doctest normalizewhitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention from math import isclose iscloseimagedistance10 40 13 33333333 true from math import isclose iscloseimagedistance1 5 6 7 1 932692308 true imagedistance0 0 doctest normalizewhitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention from math import isclose isclose focal_length 10 20 6 66666666666666 true from math import isclose isclose focal_length 9 5 6 7 3 929012346 true focal_length 0 20 doctest normalize_whitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention from math import isclose isclose object_distance 30 20 60 0 true from math import isclose isclose object_distance 10 5 11 7 102 375 true object_distance 90 0 doctest normalize_whitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention from math import isclose isclose image_distance 10 40 13 33333333 true from math import isclose isclose image_distance 1 5 6 7 1 932692308 true image_distance 0 0 doctest normalize_whitespace traceback most recent call last valueerror invalid inputs enter non zero values with respect to the sign convention
def focal_length(distance_of_object: float, distance_of_image: float) -> float: if distance_of_object == 0 or distance_of_image == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) focal_length = 1 / ((1 / distance_of_object) + (1 / distance_of_image)) return focal_length def object_distance(focal_length: float, distance_of_image: float) -> float: if distance_of_image == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) object_distance = 1 / ((1 / focal_length) - (1 / distance_of_image)) return object_distance def image_distance(focal_length: float, distance_of_object: float) -> float: if distance_of_object == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) image_distance = 1 / ((1 / focal_length) - (1 / distance_of_object)) return image_distance
in physics and astronomy a gravitational nbody simulation is a simulation of a dynamical system of particles under the influence of gravity the system consists of a number of bodies each of which exerts a gravitational force on all other bodies these forces are calculated using newton s law of universal gravitation the euler method is used at each timestep to calculate the change in velocity and position brought about by these forces softening is used to prevent numerical divergences when a particle comes too close to another and the force goes to infinity description adapted from https en wikipedia orgwikinbodysimulation see also http www shodor orgrefdeskresourcesalgorithmseulersmethod frame rate of the animation time between time steps in seconds the parameters size color are not relevant for the simulation itself they are only used for plotting euler algorithm for velocity body1 body0 0 0 0 body1 updatevelocity1 0 1 body1 velocity 1 0 0 0 body1 updatevelocity1 0 1 body1 velocity 2 0 0 0 body2 body0 0 5 0 body2 updatevelocity0 10 10 body2 velocity 5 0 100 0 body2 updatevelocity0 10 10 body2 velocity 5 0 200 0 euler algorithm for position body1 body0 0 1 0 body1 updateposition1 body1 position 1 0 0 0 body1 updateposition1 body1 position 2 0 0 0 body2 body10 10 0 2 body2 updateposition1 body2 position 10 0 8 0 body2 updateposition1 body2 position 10 0 6 0 this class is used to hold the bodies the gravitation constant the time factor and the softening factor the time factor is used to control the speed of the simulation the softening factor is used for softening a numerical trick for nbody simulations to prevent numerical divergences when two bodies get too close to each other for each body loop through all other bodies to calculate the total force they exert on it use that force to update the body s velocity bodysystem1 bodysystembody0 0 0 0 body10 0 0 0 lenbodysystem1 2 bodysystem1 updatesystem1 bodysystem1 bodies0 position 0 01 0 0 bodysystem1 bodies0 velocity 0 01 0 0 bodysystem2 bodysystembody10 0 0 0 body10 0 0 0 mass4 1 10 bodysystem2 updatesystem1 bodysystem2 bodies0 position 9 0 0 0 bodysystem2 bodies0 velocity 0 1 0 0 calculation of the distance using pythagoras s theorem extra factor due to the softening technique newton s law of universal gravitation update the body s velocity once all the force components have been added update the positions only after all the velocities have been updated updates the bodysystem and applies the change to the patchlist used for plotting bodysystem1 bodysystembody0 0 0 0 body10 0 0 0 patches1 plt circlebody positionx body positiony body size fcbody colorfor body in bodysystem1 bodies doctest ellipsis updatestepbodysystem1 1 patches1 patches10 center 0 01 0 0 bodysystem2 bodysystembody10 0 0 0 body10 0 0 0 mass4 1 10 patches2 plt circlebody positionx body positiony body size fcbody colorfor body in bodysystem2 bodies doctest ellipsis updatestepbodysystem2 1 patches2 patches20 center 9 0 0 0 update the positions of the bodies update the positions of the patches utility function to plot how the given bodysystem evolves over time no doctest provided since this function does not have a return value each body is drawn as a patch by the pltfunction function called at each step of the animation example 1 figure8 solution to the 3bodyproblem this example can be seen as a test of the implementation given the right initial conditions the bodies should move in a figure8 initial conditions taken from http www artcompsci orgvol1v1webnode56 html bodysystem example1 lenbodysystem 3 example 2 moon s orbit around the earth this example can be seen as a test of the implementation given the right initial conditions the moon should orbit around the earth as it actually does mass velocity and distance taken from https en wikipedia orgwikiearth and https en wikipedia orgwikimoon no doctest provided since this function does not have a return value calculation of the respective velocities so that total impulse is zero i e the two bodies together don t move example 3 random system with many bodies no doctest provided since this function does not have a return value bodies are created pairwise with opposite velocities so that the total impulse remains zero frame rate of the animation time between time steps in seconds the parameters size color are not relevant for the simulation itself they are only used for plotting euler algorithm for velocity body_1 body 0 0 0 0 body_1 update_velocity 1 0 1 body_1 velocity 1 0 0 0 body_1 update_velocity 1 0 1 body_1 velocity 2 0 0 0 body_2 body 0 0 5 0 body_2 update_velocity 0 10 10 body_2 velocity 5 0 100 0 body_2 update_velocity 0 10 10 body_2 velocity 5 0 200 0 euler algorithm for position body_1 body 0 0 1 0 body_1 update_position 1 body_1 position 1 0 0 0 body_1 update_position 1 body_1 position 2 0 0 0 body_2 body 10 10 0 2 body_2 update_position 1 body_2 position 10 0 8 0 body_2 update_position 1 body_2 position 10 0 6 0 this class is used to hold the bodies the gravitation constant the time factor and the softening factor the time factor is used to control the speed of the simulation the softening factor is used for softening a numerical trick for n body simulations to prevent numerical divergences when two bodies get too close to each other for each body loop through all other bodies to calculate the total force they exert on it use that force to update the body s velocity body_system_1 bodysystem body 0 0 0 0 body 10 0 0 0 len body_system_1 2 body_system_1 update_system 1 body_system_1 bodies 0 position 0 01 0 0 body_system_1 bodies 0 velocity 0 01 0 0 body_system_2 bodysystem body 10 0 0 0 body 10 0 0 0 mass 4 1 10 body_system_2 update_system 1 body_system_2 bodies 0 position 9 0 0 0 body_system_2 bodies 0 velocity 0 1 0 0 calculation of the distance using pythagoras s theorem extra factor due to the softening technique newton s law of universal gravitation update the body s velocity once all the force components have been added update the positions only after all the velocities have been updated updates the body system and applies the change to the patch list used for plotting body_system_1 bodysystem body 0 0 0 0 body 10 0 0 0 patches_1 plt circle body position_x body position_y body size fc body color for body in body_system_1 bodies doctest ellipsis update_step body_system_1 1 patches_1 patches_1 0 center 0 01 0 0 body_system_2 bodysystem body 10 0 0 0 body 10 0 0 0 mass 4 1 10 patches_2 plt circle body position_x body position_y body size fc body color for body in body_system_2 bodies doctest ellipsis update_step body_system_2 1 patches_2 patches_2 0 center 9 0 0 0 update the positions of the bodies update the positions of the patches utility function to plot how the given body system evolves over time no doctest provided since this function does not have a return value set section to be plotted fix aspect ratio each body is drawn as a patch by the plt function function called at each step of the animation noqa f841 example 1 figure 8 solution to the 3 body problem this example can be seen as a test of the implementation given the right initial conditions the bodies should move in a figure 8 initial conditions taken from http www artcompsci org vol_1 v1_web node56 html body_system example_1 len body_system 3 example 2 moon s orbit around the earth this example can be seen as a test of the implementation given the right initial conditions the moon should orbit around the earth as it actually does mass velocity and distance taken from https en wikipedia org wiki earth and https en wikipedia org wiki moon no doctest provided since this function does not have a return value calculation of the respective velocities so that total impulse is zero i e the two bodies together don t move example 3 random system with many bodies no doctest provided since this function does not have a return value bodies are created pairwise with opposite velocities so that the total impulse remains zero
from __future__ import annotations import random from matplotlib import animation from matplotlib import pyplot as plt INTERVAL = 20 DELTA_TIME = INTERVAL / 1000 class Body: def __init__( self, position_x: float, position_y: float, velocity_x: float, velocity_y: float, mass: float = 1.0, size: float = 1.0, color: str = "blue", ) -> None: self.position_x = position_x self.position_y = position_y self.velocity_x = velocity_x self.velocity_y = velocity_y self.mass = mass self.size = size self.color = color @property def position(self) -> tuple[float, float]: return self.position_x, self.position_y @property def velocity(self) -> tuple[float, float]: return self.velocity_x, self.velocity_y def update_velocity( self, force_x: float, force_y: float, delta_time: float ) -> None: self.velocity_x += force_x * delta_time self.velocity_y += force_y * delta_time def update_position(self, delta_time: float) -> None: self.position_x += self.velocity_x * delta_time self.position_y += self.velocity_y * delta_time class BodySystem: def __init__( self, bodies: list[Body], gravitation_constant: float = 1.0, time_factor: float = 1.0, softening_factor: float = 0.0, ) -> None: self.bodies = bodies self.gravitation_constant = gravitation_constant self.time_factor = time_factor self.softening_factor = softening_factor def __len__(self) -> int: return len(self.bodies) def update_system(self, delta_time: float) -> None: for body1 in self.bodies: force_x = 0.0 force_y = 0.0 for body2 in self.bodies: if body1 != body2: dif_x = body2.position_x - body1.position_x dif_y = body2.position_y - body1.position_y distance = (dif_x**2 + dif_y**2 + self.softening_factor) ** ( 1 / 2 ) force_x += ( self.gravitation_constant * body2.mass * dif_x / distance**3 ) force_y += ( self.gravitation_constant * body2.mass * dif_y / distance**3 ) body1.update_velocity(force_x, force_y, delta_time * self.time_factor) for body in self.bodies: body.update_position(delta_time * self.time_factor) def update_step( body_system: BodySystem, delta_time: float, patches: list[plt.Circle] ) -> None: body_system.update_system(delta_time) for patch, body in zip(patches, body_system.bodies): patch.center = (body.position_x, body.position_y) def plot( title: str, body_system: BodySystem, x_start: float = -1, x_end: float = 1, y_start: float = -1, y_end: float = 1, ) -> None: fig = plt.figure() fig.canvas.manager.set_window_title(title) ax = plt.axes( xlim=(x_start, x_end), ylim=(y_start, y_end) ) plt.gca().set_aspect("equal") patches = [ plt.Circle((body.position_x, body.position_y), body.size, fc=body.color) for body in body_system.bodies ] for patch in patches: ax.add_patch(patch) def update(frame: int) -> list[plt.Circle]: update_step(body_system, DELTA_TIME, patches) return patches anim = animation.FuncAnimation( fig, update, interval=INTERVAL, blit=True ) plt.show() def example_1() -> BodySystem: position_x = 0.9700436 position_y = -0.24308753 velocity_x = 0.466203685 velocity_y = 0.43236573 bodies1 = [ Body(position_x, position_y, velocity_x, velocity_y, size=0.2, color="red"), Body(-position_x, -position_y, velocity_x, velocity_y, size=0.2, color="green"), Body(0, 0, -2 * velocity_x, -2 * velocity_y, size=0.2, color="blue"), ] return BodySystem(bodies1, time_factor=3) def example_2() -> BodySystem: moon_mass = 7.3476e22 earth_mass = 5.972e24 velocity_dif = 1022 earth_moon_distance = 384399000 gravitation_constant = 6.674e-11 moon_velocity = earth_mass * velocity_dif / (earth_mass + moon_mass) earth_velocity = moon_velocity - velocity_dif moon = Body(-earth_moon_distance, 0, 0, moon_velocity, moon_mass, 10000000, "grey") earth = Body(0, 0, 0, earth_velocity, earth_mass, 50000000, "blue") return BodySystem([earth, moon], gravitation_constant, time_factor=1000000) def example_3() -> BodySystem: bodies = [] for _ in range(10): velocity_x = random.uniform(-0.5, 0.5) velocity_y = random.uniform(-0.5, 0.5) bodies.append( Body( random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5), velocity_x, velocity_y, size=0.05, ) ) bodies.append( Body( random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5), -velocity_x, -velocity_y, size=0.05, ) ) return BodySystem(bodies, 0.01, 10, 0.1) if __name__ == "__main__": plot("Figure-8 solution to the 3-body-problem", example_1(), -2, 2, -2, 2) plot( "Moon's orbit around the earth", example_2(), -430000000, 430000000, -430000000, 430000000, ) plot("Random system with many bodies", example_3(), -1.5, 1.5, -1.5, 1.5)
title finding the value of either gravitational force one of the masses or distance provided that the other three parameters are given description newton s law of universal gravitation explains the presence of force of attraction between bodies having a definite mass situated at a distance it is usually stated as that every particle attracts every other particle in the universe with a force that is directly proportional to the product of their masses and inversely proportional to the square of the distance between their centers the publication of the theory has become known as the first great unification as it marked the unification of the previously described phenomena of gravity on earth with known astronomical behaviors the equation for the universal gravitation is as follows f g mass1 mass2 distance2 source https en wikipedia orgwikinewton27slawofuniversalgravitation newton 1687 philosophi naturalis principia mathematica define the gravitational constant g and the function input parameters force magnitude in newtons mass1 mass in kilograms mass2 mass in kilograms distance distance in meters returns result dict name value pair of the parameter having zero as it s value returns the value of one of the parameters specified as 0 provided the values of other parameters are given gravitationallawforce0 mass15 mass210 distance20 force 8 342875e12 gravitationallawforce7367 382 mass10 mass274 distance3048 mass1 1 385816317292268e19 gravitationallawforce36337 283 mass10 mass20 distance35584 traceback most recent call last valueerror one and only one argument must be 0 gravitationallawforce36337 283 mass1674 mass20 distance35584 traceback most recent call last valueerror mass can not be negative gravitationallawforce847938e12 mass1674 mass20 distance9374 traceback most recent call last valueerror gravitational force can not be negative run doctest define the gravitational constant g and the function unit of g m 3 kg 1 s 2 input parameters force magnitude in newtons mass_1 mass in kilograms mass_2 mass in kilograms distance distance in meters returns result dict name value pair of the parameter having zero as it s value returns the value of one of the parameters specified as 0 provided the values of other parameters are given gravitational_law force 0 mass_1 5 mass_2 10 distance 20 force 8 342875e 12 gravitational_law force 7367 382 mass_1 0 mass_2 74 distance 3048 mass_1 1 385816317292268e 19 gravitational_law force 36337 283 mass_1 0 mass_2 0 distance 35584 traceback most recent call last valueerror one and only one argument must be 0 gravitational_law force 36337 283 mass_1 674 mass_2 0 distance 35584 traceback most recent call last valueerror mass can not be negative gravitational_law force 847938e12 mass_1 674 mass_2 0 distance 9374 traceback most recent call last valueerror gravitational force can not be negative run doctest
from __future__ import annotations GRAVITATIONAL_CONSTANT = 6.6743e-11 def gravitational_law( force: float, mass_1: float, mass_2: float, distance: float ) -> dict[str, float]: product_of_mass = mass_1 * mass_2 if (force, mass_1, mass_2, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Gravitational force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if mass_1 < 0 or mass_2 < 0: raise ValueError("Mass can not be negative") if force == 0: force = GRAVITATIONAL_CONSTANT * product_of_mass / (distance**2) return {"force": force} elif mass_1 == 0: mass_1 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_2) return {"mass_1": mass_1} elif mass_2 == 0: mass_2 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_1) return {"mass_2": mass_2} elif distance == 0: distance = (GRAVITATIONAL_CONSTANT * product_of_mass / (force)) ** 0.5 return {"distance": distance} raise ValueError("One and only one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
description newton s second law of motion pertains to the behavior of objects for which all existing forces are not balanced the second law states that the acceleration of an object is dependent upon two variables the net force acting upon the object and the mass of the object the acceleration of an object depends directly upon the net force acting upon the object and inversely upon the mass of the object as the force acting upon an object is increased the acceleration of the object is increased as the mass of an object is increased the acceleration of the object is decreased source https www physicsclassroom comclassnewtlawslesson3newtonssecondlaw formulation fnet m a diagrammatic explanation forces are unbalanced v there is acceleration the acceleration the acceleration depends directly depends inversely on the net force upon the object s mass units 1 newton 1 kg x meters seconds2 how to use inputs name units type mass in kgs float acceleration in metersseconds2 float output name units type force in newtons float newtonssecondlawofmotion10 10 100 newtonssecondlawofmotion2 0 1 2 0 run doctest demo newtons_second_law_of_motion 10 10 100 newtons_second_law_of_motion 2 0 1 2 0 run doctest demo
def newtons_second_law_of_motion(mass: float, acceleration: float) -> float: force = 0.0 try: force = mass * acceleration except Exception: return -0.0 return force if __name__ == "__main__": import doctest doctest.testmod() mass = 12.5 acceleration = 10 force = newtons_second_law_of_motion(mass, acceleration) print("The force is ", force, "N")
the photoelectric effect is the emission of electrons when electromagnetic radiation such as light hits a material electrons emitted in this manner are called photoelectrons in 1905 einstein proposed a theory of the photoelectric effect using a concept that light consists of tiny packets of energy known as photons or light quanta each packet carries energy hv that is proportional to the frequency v of the corresponding electromagnetic wave the proportionality constant h has become known as the planck constant in the range of kinetic energies of the electrons that are removed from their varying atomic bindings by the absorption of a photon of energy hv the highest kinetic energy kmax is kmax hvw here w is the minimum energy required to remove an electron from the surface of the material it is called the work function of the surface reference https en wikipedia orgwikiphotoelectriceffect calculates the maximum kinetic energy of emitted electron from the surface if the maximum kinetic energy is zero then no electron will be emitted or given electromagnetic wave frequency is small frequency float frequency of electromagnetic wave workfunction float work function of the surface inev optionalbool pass true if values are in ev usage example maximumkineticenergy1000000 2 0 maximumkineticenergy1000000 2 true 0 maximumkineticenergy10000000000000000 2 true 39 357000000000006 maximumkineticenergy9 20 traceback most recent call last valueerror frequency can t be negative maximumkineticenergy1000 a traceback most recent call last typeerror unsupported operand types for float and str in si js in evs calculates the maximum kinetic energy of emitted electron from the surface if the maximum kinetic energy is zero then no electron will be emitted or given electromagnetic wave frequency is small frequency float frequency of electromagnetic wave work_function float work function of the surface in_ev optional bool pass true if values are in ev usage example maximum_kinetic_energy 1000000 2 0 maximum_kinetic_energy 1000000 2 true 0 maximum_kinetic_energy 10000000000000000 2 true 39 357000000000006 maximum_kinetic_energy 9 20 traceback most recent call last valueerror frequency can t be negative maximum_kinetic_energy 1000 a traceback most recent call last typeerror unsupported operand type s for float and str
PLANCK_CONSTANT_JS = 6.6261 * pow(10, -34) PLANCK_CONSTANT_EVS = 4.1357 * pow(10, -15) def maximum_kinetic_energy( frequency: float, work_function: float, in_ev: bool = False ) -> float: if frequency < 0: raise ValueError("Frequency can't be negative.") if in_ev: return max(PLANCK_CONSTANT_EVS * frequency - work_function, 0) return max(PLANCK_CONSTANT_JS * frequency - work_function, 0) if __name__ == "__main__": import doctest doctest.testmod()
finding the gravitational potential energy of an object with reference to the earth by taking its mass and height above the ground as input description gravitational energy or gravitational potential energy is the potential energy a massive object has in relation to another massive object due to gravity it is the potential energy associated with the gravitational field which is released converted into kinetic energy when the objects fall towards each other gravitational potential energy increases when two objects are brought further apart for two pairwise interacting point particles the gravitational potential energy u is given by ugmmr where m and m are the masses of the two particles r is the distance between them and g is the gravitational constant close to the earth s surface the gravitational field is approximately constant and the gravitational potential energy of an object reduces to umgh where m is the object s mass ggmr is the gravity of earth and h is the height of the object s center of mass above a chosen reference level reference https en m wikipedia orgwikigravitationalenergy function will accept mass and height as parameters and return potential energy potentialenergy10 10 980 665 potentialenergy0 5 0 0 potentialenergy8 0 0 0 potentialenergy10 5 490 3325 potentialenergy0 0 0 0 potentialenergy2 8 156 9064 potentialenergy20 100 19613 3 handling of negative values of mass handling of negative values of height finding the gravitational potential energy of an object with reference to the earth by taking its mass and height above the ground as input description gravitational energy or gravitational potential energy is the potential energy a massive object has in relation to another massive object due to gravity it is the potential energy associated with the gravitational field which is released converted into kinetic energy when the objects fall towards each other gravitational potential energy increases when two objects are brought further apart for two pairwise interacting point particles the gravitational potential energy u is given by u gmm r where m and m are the masses of the two particles r is the distance between them and g is the gravitational constant close to the earth s surface the gravitational field is approximately constant and the gravitational potential energy of an object reduces to u mgh where m is the object s mass g gm r² is the gravity of earth and h is the height of the object s center of mass above a chosen reference level reference https en m wikipedia org wiki gravitational_energy function will accept mass and height as parameters and return potential energy potential_energy 10 10 980 665 potential_energy 0 5 0 0 potential_energy 8 0 0 0 potential_energy 10 5 490 3325 potential_energy 0 0 0 0 potential_energy 2 8 156 9064 potential_energy 20 100 19613 3 handling of negative values of mass handling of negative values of height
from scipy.constants import g def potential_energy(mass: float, height: float) -> float: if mass < 0: raise ValueError("The mass of a body cannot be negative") if height < 0: raise ValueError("The height above the ground cannot be negative") return mass * g * height if __name__ == "__main__": from doctest import testmod testmod(name="potential_energy")
title computing the reynolds number to find out the type of flow laminar or turbulent reynolds number is a dimensionless quantity that is used to determine the type of flow pattern as laminar or turbulent while flowing through a pipe reynolds number is defined by the ratio of inertial forces to that of viscous forces r inertial forces viscous forces r v d where density of fluid in kgm3 d diameter of pipe through which fluid flows in m v velocity of flow of the fluid in ms viscosity of the fluid in nsm2 if the reynolds number calculated is high greater than 2000 then the flow through the pipe is said to be turbulent if reynolds number is low less than 2000 the flow is said to be laminar numerically these are acceptable values although in general the laminar and turbulent flows are classified according to a range laminar flow falls below reynolds number of 1100 and turbulent falls in a range greater than 2200 laminar flow is the type of flow in which the fluid travels smoothly in regular paths conversely turbulent flow isn t smooth and follows an irregular path with lots of mixing reference https byjus comphysicsreynoldsnumber reynoldsnumber900 2 5 0 05 0 4 281 25 reynoldsnumber450 3 86 0 078 0 23 589 0695652173912 reynoldsnumber234 4 5 0 3 0 44 717 9545454545454 reynoldsnumber90 2 0 045 1 traceback most recent call last valueerror please ensure that density diameter and viscosity are positive reynoldsnumber0 2 0 4 2 traceback most recent call last valueerror please ensure that density diameter and viscosity are positive reynolds_number 900 2 5 0 05 0 4 281 25 reynolds_number 450 3 86 0 078 0 23 589 0695652173912 reynolds_number 234 4 5 0 3 0 44 717 9545454545454 reynolds_number 90 2 0 045 1 traceback most recent call last valueerror please ensure that density diameter and viscosity are positive reynolds_number 0 2 0 4 2 traceback most recent call last valueerror please ensure that density diameter and viscosity are positive
def reynolds_number( density: float, velocity: float, diameter: float, viscosity: float ) -> float: if density <= 0 or diameter <= 0 or viscosity <= 0: raise ValueError( "please ensure that density, diameter and viscosity are positive" ) return (density * abs(velocity) * diameter) / viscosity if __name__ == "__main__": import doctest doctest.testmod()
the rootmeansquare speed is essential in measuring the average speed of particles contained in a gas defined as vrms 3rtm in kinetic molecular theory gasified particles are in a condition of constant random motion each particle moves at a completely different pace perpetually clashing and changing directions consistently velocity is used to describe the movement of gas particles thereby taking into account both speed and direction although the velocity of gaseous particles is constantly changing the distribution of velocities does not change we cannot gauge the velocity of every individual particle thus we frequently reason in terms of the particles average behavior particles moving in opposite directions have velocities of opposite signs since gas particles are in random motion it s plausible that there ll be about as several moving in one direction as within the other way which means that the average velocity for a collection of gas particles equals zero as this value is unhelpful the average of velocities can be determined using an alternative method rmsspeedofmolecule100 2 35 315279554323226 rmsspeedofmolecule273 12 23 821458421977443 run doctest example rms_speed_of_molecule 100 2 35 315279554323226 rms_speed_of_molecule 273 12 23 821458421977443 run doctest example
UNIVERSAL_GAS_CONSTANT = 8.3144598 def rms_speed_of_molecule(temperature: float, molar_mass: float) -> float: if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod() temperature = 300 molar_mass = 28 vrms = rms_speed_of_molecule(temperature, molar_mass) print(f"Vrms of Nitrogen gas at 300 K is {vrms} m/s")
shear stress is a component of stress that is coplanar to the material crosssection it arises due to a shear force the component of the force vector parallel to the material crosssection https en wikipedia orgwikishearstress this function can calculate any one of the three 1 shear stress 2 tangential force 3 crosssectional area this is calculated from the other two provided values examples shearstressstress25 tangentialforce100 area0 area 4 0 shearstressstress0 tangentialforce1600 area200 stress 8 0 shearstressstress1000 tangentialforce0 area1200 tangentialforce 1200000 shear stress is a component of stress that is coplanar to the material cross section it arises due to a shear force the component of the force vector parallel to the material cross section https en wikipedia org wiki shear_stress this function can calculate any one of the three 1 shear stress 2 tangential force 3 cross sectional area this is calculated from the other two provided values examples shear_stress stress 25 tangential_force 100 area 0 area 4 0 shear_stress stress 0 tangential_force 1600 area 200 stress 8 0 shear_stress stress 1000 tangential_force 0 area 1200 tangential_force 1200000
from __future__ import annotations def shear_stress( stress: float, tangential_force: float, area: float, ) -> tuple[str, float]: if (stress, tangential_force, area).count(0) != 1: raise ValueError("You cannot supply more or less than 2 values") elif stress < 0: raise ValueError("Stress cannot be negative") elif tangential_force < 0: raise ValueError("Tangential Force cannot be negative") elif area < 0: raise ValueError("Area cannot be negative") elif stress == 0: return ( "stress", tangential_force / area, ) elif tangential_force == 0: return ( "tangential_force", stress * area, ) else: return ( "area", tangential_force / stress, ) if __name__ == "__main__": import doctest doctest.testmod()
title calculating the speed of sound description the speed of sound c is the speed that a sound wave travels per unit time ms during propagation the sound wave propagates through an elastic medium sound propagates as longitudinal waves in liquids and gases and as transverse waves in solids this file calculates the speed of sound in a fluid based on its bulk module and density equation for the speed of sound in a fluid cfluid sqrtks p cfluid speed of sound in fluid ks isentropic bulk modulus p density of fluid source https en wikipedia orgwikispeedofsound calculates the speed of sound in a fluid from its density and bulk modulus examples example 1 water 20c bulkmodulus 2 15mpa density998kgm example 2 mercury 20c bulkmodulus 28 5mpa density13600kgm speedofsoundinafluidbulkmodulus2 15e9 density998 1467 7563207952705 speedofsoundinafluidbulkmodulus28 5e9 density13600 1447 614670861731 calculates the speed of sound in a fluid from its density and bulk modulus examples example 1 water 20 c bulk_modulus 2 15mpa density 998kg m³ example 2 mercury 20 c bulk_modulus 28 5mpa density 13600kg m³ speed_of_sound_in_a_fluid bulk_modulus 2 15e9 density 998 1467 7563207952705 speed_of_sound_in_a_fluid bulk_modulus 28 5e9 density 13600 1447 614670861731
def speed_of_sound_in_a_fluid(density: float, bulk_modulus: float) -> float: if density <= 0: raise ValueError("Impossible fluid density") if bulk_modulus <= 0: raise ValueError("Impossible bulk modulus") return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
the rootmeansquare average and most probable speeds of gas molecules are derived from the maxwellboltzmann distribution the maxwellboltzmann distribution is a probability distribution that describes the distribution of speeds of particles in an ideal gas the distribution is given by the following equation fv m2rt32 4v2 emv22rt where fv is the fraction of molecules with a speed v m is the molar mass of the gas in kgmol r is the gas constant t is the absolute temperature more information about the maxwellboltzmann distribution can be found here https en wikipedia orgwikimaxwelle28093boltzmanndistribution the average speed can be calculated by integrating the maxwellboltzmann distribution from 0 to infinity and dividing by the total number of molecules the result is vavg 8rtm the most probable speed is the speed at which the maxwellboltzmann distribution is at its maximum this can be found by differentiating the maxwellboltzmann distribution with respect to v and setting the result equal to zero the result is vmp 2rtm the rootmeansquare speed is another measure of the average speed of the molecules in a gas it is calculated by taking the square root of the average of the squares of the speeds of the molecules the result is vrms 3rtm here we have defined functions to calculate the average and most probable speeds of molecules in a gas given the temperature and molar mass of the gas import the constants r and pi from the scipy constants library takes the temperature in k and molar mass in kgmol of a gas and returns the average speed of a molecule in the gas in ms examples avgspeedofmolecule273 0 028 nitrogen at 273 k 454 3488755020387 avgspeedofmolecule300 0 032 oxygen at 300 k 445 52572733919885 avgspeedofmolecule273 0 028 invalid temperature traceback most recent call last exception absolute temperature cannot be less than 0 k avgspeedofmolecule273 0 invalid molar mass traceback most recent call last exception molar mass should be greater than 0 kgmol takes the temperature in k and molar mass in kgmol of a gas and returns the most probable speed of a molecule in the gas in ms examples mpsspeedofmolecule273 0 028 nitrogen at 273 k 402 65620701908966 mpsspeedofmolecule300 0 032 oxygen at 300 k 394 836895549922 mpsspeedofmolecule273 0 028 invalid temperature traceback most recent call last exception absolute temperature cannot be less than 0 k mpsspeedofmolecule273 0 invalid molar mass traceback most recent call last exception molar mass should be greater than 0 kgmol import the constants r and pi from the scipy constants library takes the temperature in k and molar mass in kg mol of a gas and returns the average speed of a molecule in the gas in m s examples avg_speed_of_molecule 273 0 028 nitrogen at 273 k 454 3488755020387 avg_speed_of_molecule 300 0 032 oxygen at 300 k 445 52572733919885 avg_speed_of_molecule 273 0 028 invalid temperature traceback most recent call last exception absolute temperature cannot be less than 0 k avg_speed_of_molecule 273 0 invalid molar mass traceback most recent call last exception molar mass should be greater than 0 kg mol takes the temperature in k and molar mass in kg mol of a gas and returns the most probable speed of a molecule in the gas in m s examples mps_speed_of_molecule 273 0 028 nitrogen at 273 k 402 65620701908966 mps_speed_of_molecule 300 0 032 oxygen at 300 k 394 836895549922 mps_speed_of_molecule 273 0 028 invalid temperature traceback most recent call last exception absolute temperature cannot be less than 0 k mps_speed_of_molecule 273 0 invalid molar mass traceback most recent call last exception molar mass should be greater than 0 kg mol
from scipy.constants import R, pi def avg_speed_of_molecule(temperature: float, molar_mass: float) -> float: if temperature < 0: raise Exception("Absolute temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass should be greater than 0 kg/mol") return (8 * R * temperature / (pi * molar_mass)) ** 0.5 def mps_speed_of_molecule(temperature: float, molar_mass: float) -> float: if temperature < 0: raise Exception("Absolute temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass should be greater than 0 kg/mol") return (2 * R * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
title computing the terminal velocity of an object falling through a fluid terminal velocity is defined as the highest velocity attained by an object falling through a fluid it is observed when the sum of drag force and buoyancy is equal to the downward gravity force acting on the object the acceleration of the object is zero as the net force acting on the object is zero vt 2 m g a cd0 5 where vt terminal velocity in ms m mass of the falling object in kg g acceleration due to gravity value taken imported from scipy density of the fluid through which the object is falling in kgm3 a projected area of the object in m2 cd drag coefficient dimensionless reference https byjus comphysicsderivationofterminalvelocity terminalvelocity1 25 0 6 0 77 1 3031197996044768 terminalvelocity2 100 0 45 0 23 1 9467947148674276 terminalvelocity5 50 0 2 0 5 4 428690551393267 terminalvelocity5 50 0 2 2 traceback most recent call last valueerror mass density area and the drag coefficient all need to be positive terminalvelocity3 20 1 2 traceback most recent call last valueerror mass density area and the drag coefficient all need to be positive terminalvelocity2 1 0 44 1 traceback most recent call last valueerror mass density area and the drag coefficient all need to be positive terminal_velocity 1 25 0 6 0 77 1 3031197996044768 terminal_velocity 2 100 0 45 0 23 1 9467947148674276 terminal_velocity 5 50 0 2 0 5 4 428690551393267 terminal_velocity 5 50 0 2 2 traceback most recent call last valueerror mass density area and the drag coefficient all need to be positive terminal_velocity 3 20 1 2 traceback most recent call last valueerror mass density area and the drag coefficient all need to be positive terminal_velocity 2 1 0 44 1 traceback most recent call last valueerror mass density area and the drag coefficient all need to be positive
from scipy.constants import g def terminal_velocity( mass: float, density: float, area: float, drag_coefficient: float ) -> float: if mass <= 0 or density <= 0 or area <= 0 or drag_coefficient <= 0: raise ValueError( "mass, density, area and the drag coefficient all need to be positive" ) return ((2 * mass * g) / (density * area * drag_coefficient)) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
project euler problem 1 https projecteuler netproblem1 multiples of 3 and 5 if we list all the natural numbers below 10 that are multiples of 3 or 5 we get 3 5 6 and 9 the sum of these multiples is 23 find the sum of all the multiples of 3 or 5 below 1000 returns the sum of all the multiples of 3 or 5 below n solution3 0 solution4 3 solution10 23 solution600 83700 solution7 0 returns the sum of all the multiples of 3 or 5 below n solution 3 0 solution 4 3 solution 10 23 solution 600 83700 solution 7 0
def solution(n: int = 1000) -> int: return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 1 https projecteuler netproblem1 multiples of 3 and 5 if we list all the natural numbers below 10 that are multiples of 3 or 5 we get 3 5 6 and 9 the sum of these multiples is 23 find the sum of all the multiples of 3 or 5 below 1000 returns the sum of all the multiples of 3 or 5 below n solution3 0 solution4 3 solution10 23 solution600 83700 returns the sum of all the multiples of 3 or 5 below n solution 3 0 solution 4 3 solution 10 23 solution 600 83700 total of an a p
def solution(n: int = 1000) -> int: total = 0 terms = (n - 1) // 3 total += ((terms) * (6 + (terms - 1) * 3)) // 2 terms = (n - 1) // 5 total += ((terms) * (10 + (terms - 1) * 5)) // 2 terms = (n - 1) // 15 total -= ((terms) * (30 + (terms - 1) * 15)) // 2 return total if __name__ == "__main__": print(f"{solution() = }")
project euler problem 1 https projecteuler netproblem1 multiples of 3 and 5 if we list all the natural numbers below 10 that are multiples of 3 or 5 we get 3 5 6 and 9 the sum of these multiples is 23 find the sum of all the multiples of 3 or 5 below 1000 this solution is based on the pattern that the successive numbers in the series follow 03 2 1 3 1 2 3 returns the sum of all the multiples of 3 or 5 below n solution3 0 solution4 3 solution10 23 solution600 83700 this solution is based on the pattern that the successive numbers in the series follow 0 3 2 1 3 1 2 3 returns the sum of all the multiples of 3 or 5 below n solution 3 0 solution 4 3 solution 10 23 solution 600 83700
def solution(n: int = 1000) -> int: total = 0 num = 0 while 1: num += 3 if num >= n: break total += num num += 2 if num >= n: break total += num num += 1 if num >= n: break total += num num += 3 if num >= n: break total += num num += 1 if num >= n: break total += num num += 2 if num >= n: break total += num num += 3 if num >= n: break total += num return total if __name__ == "__main__": print(f"{solution() = }")
project euler problem 1 https projecteuler netproblem1 multiples of 3 and 5 if we list all the natural numbers below 10 that are multiples of 3 or 5 we get 3 5 6 and 9 the sum of these multiples is 23 find the sum of all the multiples of 3 or 5 below 1000 returns the sum of all the multiples of 3 or 5 below n solution3 0 solution4 3 solution10 23 solution600 83700 returns the sum of all the multiples of 3 or 5 below n solution 3 0 solution 4 3 solution 10 23 solution 600 83700
def solution(n: int = 1000) -> int: xmulti = [] zmulti = [] z = 3 x = 5 temp = 1 while True: result = z * temp if result < n: zmulti.append(result) temp += 1 else: temp = 1 break while True: result = x * temp if result < n: xmulti.append(result) temp += 1 else: break collection = list(set(xmulti + zmulti)) return sum(collection) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 1 https projecteuler netproblem1 multiples of 3 and 5 if we list all the natural numbers below 10 that are multiples of 3 or 5 we get 3 5 6 and 9 the sum of these multiples is 23 find the sum of all the multiples of 3 or 5 below 1000 returns the sum of all the multiples of 3 or 5 below n a straightforward pythonic solution using list comprehension solution3 0 solution4 3 solution10 23 solution600 83700 returns the sum of all the multiples of 3 or 5 below n a straightforward pythonic solution using list comprehension solution 3 0 solution 4 3 solution 10 23 solution 600 83700
def solution(n: int = 1000) -> int: return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 1 https projecteuler netproblem1 multiples of 3 and 5 if we list all the natural numbers below 10 that are multiples of 3 or 5 we get 3 5 6 and 9 the sum of these multiples is 23 find the sum of all the multiples of 3 or 5 below 1000 returns the sum of all the multiples of 3 or 5 below n solution3 0 solution4 3 solution10 23 solution600 83700 returns the sum of all the multiples of 3 or 5 below n solution 3 0 solution 4 3 solution 10 23 solution 600 83700
def solution(n: int = 1000) -> int: a = 3 result = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"{solution() = }")
project euler problem 1 https projecteuler netproblem1 multiples of 3 and 5 if we list all the natural numbers below 10 that are multiples of 3 or 5 we get 3 5 6 and 9 the sum of these multiples is 23 find the sum of all the multiples of 3 or 5 below 1000 returns the sum of all the multiples of 3 or 5 below n solution3 0 solution4 3 solution10 23 solution600 83700 returns the sum of all the multiples of 3 or 5 below n solution 3 0 solution 4 3 solution 10 23 solution 600 83700
def solution(n: int = 1000) -> int: result = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: result += i return result if __name__ == "__main__": print(f"{solution() = }")
project euler problem 2 https projecteuler netproblem2 even fibonacci numbers each new term in the fibonacci sequence is generated by adding the previous two terms by starting with 1 and 2 the first 10 terms will be 1 2 3 5 8 13 21 34 55 89 by considering the terms in the fibonacci sequence whose values do not exceed four million find the sum of the evenvalued terms references https en wikipedia orgwikifibonaccinumber returns the sum of all even fibonacci sequence elements that are lower or equal to n solution10 10 solution15 10 solution2 2 solution1 0 solution34 44 returns the sum of all even fibonacci sequence elements that are lower or equal to n solution 10 10 solution 15 10 solution 2 2 solution 1 0 solution 34 44
def solution(n: int = 4000000) -> int: i = 1 j = 2 total = 0 while j <= n: if j % 2 == 0: total += j i, j = j, i + j return total if __name__ == "__main__": print(f"{solution() = }")
project euler problem 2 https projecteuler netproblem2 even fibonacci numbers each new term in the fibonacci sequence is generated by adding the previous two terms by starting with 1 and 2 the first 10 terms will be 1 2 3 5 8 13 21 34 55 89 by considering the terms in the fibonacci sequence whose values do not exceed four million find the sum of the evenvalued terms references https en wikipedia orgwikifibonaccinumber returns the sum of all even fibonacci sequence elements that are lower or equal to n solution10 10 solution15 10 solution2 2 solution1 0 solution34 44 returns the sum of all even fibonacci sequence elements that are lower or equal to n solution 10 10 solution 15 10 solution 2 2 solution 1 0 solution 34 44
def solution(n: int = 4000000) -> int: even_fibs = [] a, b = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(b) a, b = b, a + b return sum(even_fibs) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 2 https projecteuler netproblem2 even fibonacci numbers each new term in the fibonacci sequence is generated by adding the previous two terms by starting with 1 and 2 the first 10 terms will be 1 2 3 5 8 13 21 34 55 89 by considering the terms in the fibonacci sequence whose values do not exceed four million find the sum of the evenvalued terms references https en wikipedia orgwikifibonaccinumber returns the sum of all even fibonacci sequence elements that are lower or equal to n solution10 10 solution15 10 solution2 2 solution1 0 solution34 44 returns the sum of all even fibonacci sequence elements that are lower or equal to n solution 10 10 solution 15 10 solution 2 2 solution 1 0 solution 34 44
def solution(n: int = 4000000) -> int: if n <= 1: return 0 a = 0 b = 2 count = 0 while 4 * b + a <= n: a, b = b, 4 * b + a count += a return count + b if __name__ == "__main__": print(f"{solution() = }")
project euler problem 2 https projecteuler netproblem2 even fibonacci numbers each new term in the fibonacci sequence is generated by adding the previous two terms by starting with 1 and 2 the first 10 terms will be 1 2 3 5 8 13 21 34 55 89 by considering the terms in the fibonacci sequence whose values do not exceed four million find the sum of the evenvalued terms references https en wikipedia orgwikifibonaccinumber returns the sum of all even fibonacci sequence elements that are lower or equal to n solution10 10 solution15 10 solution2 2 solution1 0 solution34 44 solution3 4 2 solution0 traceback most recent call last valueerror parameter n must be greater than or equal to one solution17 traceback most recent call last valueerror parameter n must be greater than or equal to one solution traceback most recent call last typeerror parameter n must be int or castable to int solutionasd traceback most recent call last typeerror parameter n must be int or castable to int returns the sum of all even fibonacci sequence elements that are lower or equal to n solution 10 10 solution 15 10 solution 2 2 solution 1 0 solution 34 44 solution 3 4 2 solution 0 traceback most recent call last valueerror parameter n must be greater than or equal to one solution 17 traceback most recent call last valueerror parameter n must be greater than or equal to one solution traceback most recent call last typeerror parameter n must be int or castable to int solution asd traceback most recent call last typeerror parameter n must be int or castable to int
import math from decimal import Decimal, getcontext def solution(n: int = 4000000) -> int: try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") getcontext().prec = 100 phi = (Decimal(5) ** Decimal(0.5) + 1) / Decimal(2) index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2 num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2) total = num // 2 return int(total) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 2 https projecteuler netproblem2 even fibonacci numbers each new term in the fibonacci sequence is generated by adding the previous two terms by starting with 1 and 2 the first 10 terms will be 1 2 3 5 8 13 21 34 55 89 by considering the terms in the fibonacci sequence whose values do not exceed four million find the sum of the evenvalued terms references https en wikipedia orgwikifibonaccinumber returns the sum of all even fibonacci sequence elements that are lower or equal to n solution10 10 solution15 10 solution2 2 solution1 0 solution34 44 returns the sum of all even fibonacci sequence elements that are lower or equal to n solution 10 10 solution 15 10 solution 2 2 solution 1 0 solution 34 44
def solution(n: int = 4000000) -> int: fib = [0, 1] i = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1]) if fib[i + 2] > n: break i += 1 total = 0 for j in range(len(fib) - 1): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"{solution() = }")
project euler problem 3 https projecteuler netproblem3 largest prime factor the prime factors of 13195 are 5 7 13 and 29 what is the largest prime factor of the number 600851475143 references https en wikipedia orgwikiprimenumberuniquefactorization checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number i e if the result is true then the number is indeed prime else it is not isprime2 true isprime3 true isprime27 false isprime2999 true isprime0 false isprime1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the largest prime factor of a given number n solution13195 29 solution10 5 solution17 17 solution3 4 3 solution0 traceback most recent call last valueerror parameter n must be greater than or equal to one solution17 traceback most recent call last valueerror parameter n must be greater than or equal to one solution traceback most recent call last typeerror parameter n must be int or castable to int solutionasd traceback most recent call last typeerror parameter n must be int or castable to int checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number i e if the result is true then the number is indeed prime else it is not is_prime 2 true is_prime 3 true is_prime 27 false is_prime 2999 true is_prime 0 false is_prime 1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the largest prime factor of a given number n solution 13195 29 solution 10 5 solution 17 17 solution 3 4 3 solution 0 traceback most recent call last valueerror parameter n must be greater than or equal to one solution 17 traceback most recent call last valueerror parameter n must be greater than or equal to one solution traceback most recent call last typeerror parameter n must be int or castable to int solution asd traceback most recent call last typeerror parameter n must be int or castable to int
import math def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(n: int = 600851475143) -> int: try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") max_number = 0 if is_prime(n): return n while n % 2 == 0: n //= 2 if is_prime(n): return n for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: if is_prime(n // i): max_number = n // i break elif is_prime(i): max_number = i return max_number if __name__ == "__main__": print(f"{solution() = }")
project euler problem 3 https projecteuler netproblem3 largest prime factor the prime factors of 13195 are 5 7 13 and 29 what is the largest prime factor of the number 600851475143 references https en wikipedia orgwikiprimenumberuniquefactorization returns the largest prime factor of a given number n solution13195 29 solution10 5 solution17 17 solution3 4 3 solution0 traceback most recent call last valueerror parameter n must be greater than or equal to one solution17 traceback most recent call last valueerror parameter n must be greater than or equal to one solution traceback most recent call last typeerror parameter n must be int or castable to int solutionasd traceback most recent call last typeerror parameter n must be int or castable to int returns the largest prime factor of a given number n solution 13195 29 solution 10 5 solution 17 17 solution 3 4 3 solution 0 traceback most recent call last valueerror parameter n must be greater than or equal to one solution 17 traceback most recent call last valueerror parameter n must be greater than or equal to one solution traceback most recent call last typeerror parameter n must be int or castable to int solution asd traceback most recent call last typeerror parameter n must be int or castable to int
def solution(n: int = 600851475143) -> int: try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") prime = 1 i = 2 while i * i <= n: while n % i == 0: prime = i n //= i i += 1 if n > 1: prime = n return int(prime) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 3 https projecteuler netproblem3 largest prime factor the prime factors of 13195 are 5 7 13 and 29 what is the largest prime factor of the number 600851475143 references https en wikipedia orgwikiprimenumberuniquefactorization returns the largest prime factor of a given number n solution13195 29 solution10 5 solution17 17 solution3 4 3 solution0 traceback most recent call last valueerror parameter n must be greater than or equal to one solution17 traceback most recent call last valueerror parameter n must be greater than or equal to one solution traceback most recent call last typeerror parameter n must be int or castable to int solutionasd traceback most recent call last typeerror parameter n must be int or castable to int returns the largest prime factor of a given number n solution 13195 29 solution 10 5 solution 17 17 solution 3 4 3 solution 0 traceback most recent call last valueerror parameter n must be greater than or equal to one solution 17 traceback most recent call last valueerror parameter n must be greater than or equal to one solution traceback most recent call last typeerror parameter n must be int or castable to int solution asd traceback most recent call last typeerror parameter n must be int or castable to int
def solution(n: int = 600851475143) -> int: try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 2 ans = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 ans = i while n % i == 0: n = n // i i += 1 return int(ans) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 4 https projecteuler netproblem4 largest palindrome product a palindromic number reads the same both ways the largest palindrome made from the product of two 2digit numbers is 9009 91 99 find the largest palindrome made from the product of two 3digit numbers references https en wikipedia orgwikipalindromicnumber returns the largest palindrome made from the product of two 3digit numbers which is less than n solution20000 19591 solution30000 29992 solution40000 39893 solution10000 traceback most recent call last valueerror that number is larger than our acceptable range fetches the next number checks whether strnumber is a palindrome if number is a product of two 3digit numbers then number is the answer otherwise fetch next number returns the largest palindrome made from the product of two 3 digit numbers which is less than n solution 20000 19591 solution 30000 29992 solution 40000 39893 solution 10000 traceback most recent call last valueerror that number is larger than our acceptable range fetches the next number checks whether str_number is a palindrome if number is a product of two 3 digit numbers then number is the answer otherwise fetch next number
def solution(n: int = 998001) -> int: for number in range(n - 1, 9999, -1): str_number = str(number) if str_number == str_number[::-1]: divisor = 999 while divisor != 99: if (number % divisor == 0) and (len(str(number // divisor)) == 3.0): return number divisor -= 1 raise ValueError("That number is larger than our acceptable range.") if __name__ == "__main__": print(f"{solution() = }")
project euler problem 4 https projecteuler netproblem4 largest palindrome product a palindromic number reads the same both ways the largest palindrome made from the product of two 2digit numbers is 9009 91 99 find the largest palindrome made from the product of two 3digit numbers references https en wikipedia orgwikipalindromicnumber returns the largest palindrome made from the product of two 3digit numbers which is less than n solution20000 19591 solution30000 29992 solution40000 39893 returns the largest palindrome made from the product of two 3 digit numbers which is less than n solution 20000 19591 solution 30000 29992 solution 40000 39893 3 digit numbers range from 999 down to 100
def solution(n: int = 998001) -> int: answer = 0 for i in range(999, 99, -1): for j in range(999, 99, -1): product_string = str(i * j) if product_string == product_string[::-1] and i * j < n: answer = max(answer, i * j) return answer if __name__ == "__main__": print(f"{solution() = }")