diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index be8364a7..a17c4c32 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,7 +16,7 @@ repos: - id: auto-walrus - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.2.2 + rev: v0.3.2 hooks: - id: ruff - id: ruff-format @@ -47,7 +47,7 @@ repos: - id: validate-pyproject - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.8.0 + rev: v1.9.0 hooks: - id: mypy args: diff --git a/backtracking/all_combinations.py b/backtracking/all_combinations.py index 40730494..390decf3 100644 --- a/backtracking/all_combinations.py +++ b/backtracking/all_combinations.py @@ -1,9 +1,10 @@ """ - In this problem, we want to determine all possible combinations of k - numbers out of 1 ... n. We use backtracking to solve this problem. +In this problem, we want to determine all possible combinations of k +numbers out of 1 ... n. We use backtracking to solve this problem. - Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))), +Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))), """ + from __future__ import annotations from itertools import combinations diff --git a/backtracking/all_permutations.py b/backtracking/all_permutations.py index ff8a53e0..c483cd62 100644 --- a/backtracking/all_permutations.py +++ b/backtracking/all_permutations.py @@ -1,10 +1,11 @@ """ - In this problem, we want to determine all possible permutations - of the given sequence. We use backtracking to solve this problem. +In this problem, we want to determine all possible permutations +of the given sequence. We use backtracking to solve this problem. - Time complexity: O(n! * n), - where n denotes the length of the given sequence. +Time complexity: O(n! * n), +where n denotes the length of the given sequence. """ + from __future__ import annotations diff --git a/backtracking/all_subsequences.py b/backtracking/all_subsequences.py index c465fc54..7844a829 100644 --- a/backtracking/all_subsequences.py +++ b/backtracking/all_subsequences.py @@ -5,6 +5,7 @@ of the given sequence. We use backtracking to solve this problem. Time complexity: O(2^n), where n denotes the length of the given sequence. """ + from __future__ import annotations from typing import Any diff --git a/backtracking/coloring.py b/backtracking/coloring.py index 9d539de8..f10cdbcf 100644 --- a/backtracking/coloring.py +++ b/backtracking/coloring.py @@ -1,9 +1,9 @@ """ - Graph Coloring also called "m coloring problem" - consists of coloring a given graph with at most m colors - such that no adjacent vertices are assigned the same color +Graph Coloring also called "m coloring problem" +consists of coloring a given graph with at most m colors +such that no adjacent vertices are assigned the same color - Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring +Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring """ diff --git a/backtracking/hamiltonian_cycle.py b/backtracking/hamiltonian_cycle.py index e9916f83..f6e4212e 100644 --- a/backtracking/hamiltonian_cycle.py +++ b/backtracking/hamiltonian_cycle.py @@ -1,10 +1,10 @@ """ - A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle - through a graph that visits each node exactly once. - Determining whether such paths and cycles exist in graphs - is the 'Hamiltonian path problem', which is NP-complete. +A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle +through a graph that visits each node exactly once. +Determining whether such paths and cycles exist in graphs +is the 'Hamiltonian path problem', which is NP-complete. - Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path +Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path """ diff --git a/backtracking/minimax.py b/backtracking/minimax.py index 6dece299..4eef90b7 100644 --- a/backtracking/minimax.py +++ b/backtracking/minimax.py @@ -7,6 +7,7 @@ if move is of maximizer return true else false leaves of game tree is stored in scores[] height is maximum height of Game tree """ + from __future__ import annotations import math diff --git a/backtracking/n_queens.py b/backtracking/n_queens.py index 2cd8c703..81668b17 100644 --- a/backtracking/n_queens.py +++ b/backtracking/n_queens.py @@ -1,12 +1,13 @@ """ - The nqueens problem is of placing N queens on a N * N - chess board such that no queen can attack any other queens placed - on that chess board. - This means that one queen cannot have any other queen on its horizontal, vertical and - diagonal lines. +The nqueens problem is of placing N queens on a N * N +chess board such that no queen can attack any other queens placed +on that chess board. +This means that one queen cannot have any other queen on its horizontal, vertical and +diagonal lines. """ + from __future__ import annotations solution = [] diff --git a/backtracking/n_queens_math.py b/backtracking/n_queens_math.py index f3b08ab0..287d1f09 100644 --- a/backtracking/n_queens_math.py +++ b/backtracking/n_queens_math.py @@ -75,6 +75,7 @@ Applying these two formulas we can check if a queen in some position is being at for another one or vice versa. """ + from __future__ import annotations diff --git a/backtracking/sudoku.py b/backtracking/sudoku.py index 6e4e3e87..8f5459c7 100644 --- a/backtracking/sudoku.py +++ b/backtracking/sudoku.py @@ -9,6 +9,7 @@ function on the next column to see if it returns True. if yes, we have solved the puzzle. else, we backtrack and place another number in that cell and repeat this process. """ + from __future__ import annotations Matrix = list[list[int]] diff --git a/backtracking/sum_of_subsets.py b/backtracking/sum_of_subsets.py index c5e23321..f34d3ca3 100644 --- a/backtracking/sum_of_subsets.py +++ b/backtracking/sum_of_subsets.py @@ -1,11 +1,12 @@ """ - The sum-of-subsetsproblem states that a set of non-negative integers, and a - value M, determine all possible subsets of the given set whose summation sum - equal to given M. +The sum-of-subsetsproblem states that a set of non-negative integers, and a +value M, determine all possible subsets of the given set whose summation sum +equal to given M. - Summation of the chosen numbers must be equal to given number M and one number - can be used only once. +Summation of the chosen numbers must be equal to given number M and one number +can be used only once. """ + from __future__ import annotations diff --git a/boolean_algebra/nor_gate.py b/boolean_algebra/nor_gate.py index 0c8ab1c0..d4d6f0da 100644 --- a/boolean_algebra/nor_gate.py +++ b/boolean_algebra/nor_gate.py @@ -12,6 +12,7 @@ Following is the truth table of a NOR Gate: Code provided by Akshaj Vishwanathan https://www.geeksforgeeks.org/logic-gates-in-python """ + from collections.abc import Callable diff --git a/cellular_automata/conways_game_of_life.py b/cellular_automata/conways_game_of_life.py index 84f4d5be..364a34c3 100644 --- a/cellular_automata/conways_game_of_life.py +++ b/cellular_automata/conways_game_of_life.py @@ -2,6 +2,7 @@ Conway's Game of Life implemented in Python. https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life """ + from __future__ import annotations from PIL import Image diff --git a/cellular_automata/game_of_life.py b/cellular_automata/game_of_life.py index d691a2b7..67e647d6 100644 --- a/cellular_automata/game_of_life.py +++ b/cellular_automata/game_of_life.py @@ -26,7 +26,8 @@ Game-Of-Life Rules: 4. Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. - """ +""" + import random import sys diff --git a/cellular_automata/nagel_schrekenberg.py b/cellular_automata/nagel_schrekenberg.py index 3fd6afca..bcdca902 100644 --- a/cellular_automata/nagel_schrekenberg.py +++ b/cellular_automata/nagel_schrekenberg.py @@ -24,6 +24,7 @@ Examples for doctest: >>> simulate(construct_highway(5, 2, -2), 3, 0, 2) [[0, -1, 0, -1, 0], [0, -1, 0, -1, -1], [0, -1, -1, 1, -1], [-1, 1, -1, 0, -1]] """ + from random import randint, random diff --git a/ciphers/a1z26.py b/ciphers/a1z26.py index 0f0eb7c5..a1377ea6 100644 --- a/ciphers/a1z26.py +++ b/ciphers/a1z26.py @@ -5,6 +5,7 @@ corresponding to the character's position in the alphabet. https://www.dcode.fr/letter-number-cipher http://bestcodes.weebly.com/a1z26.html """ + from __future__ import annotations diff --git a/ciphers/atbash.py b/ciphers/atbash.py index 0a86a800..4e8f663e 100644 --- a/ciphers/atbash.py +++ b/ciphers/atbash.py @@ -1,4 +1,5 @@ -""" https://en.wikipedia.org/wiki/Atbash """ +"""https://en.wikipedia.org/wiki/Atbash""" + import string diff --git a/ciphers/base32.py b/ciphers/base32.py index 1924d1e1..911afa24 100644 --- a/ciphers/base32.py +++ b/ciphers/base32.py @@ -3,6 +3,7 @@ Base32 encoding and decoding https://en.wikipedia.org/wiki/Base32 """ + B32_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" diff --git a/ciphers/enigma_machine2.py b/ciphers/enigma_machine2.py index ec0d44e4..163aa717 100644 --- a/ciphers/enigma_machine2.py +++ b/ciphers/enigma_machine2.py @@ -14,6 +14,7 @@ Module includes: Created by TrapinchO """ + from __future__ import annotations RotorPositionT = tuple[int, int, int] diff --git a/ciphers/fractionated_morse_cipher.py b/ciphers/fractionated_morse_cipher.py index c1d5dc6d..6c4c415a 100644 --- a/ciphers/fractionated_morse_cipher.py +++ b/ciphers/fractionated_morse_cipher.py @@ -8,6 +8,7 @@ making it more secure than substitution ciphers. http://practicalcryptography.com/ciphers/fractionated-morse-cipher/ """ + import string MORSE_CODE_DICT = { diff --git a/ciphers/hill_cipher.py b/ciphers/hill_cipher.py index 1201fda9..ea337a72 100644 --- a/ciphers/hill_cipher.py +++ b/ciphers/hill_cipher.py @@ -35,6 +35,7 @@ https://www.youtube.com/watch?v=kfmNeskzs2o https://www.youtube.com/watch?v=4RhLNDqcjpA """ + import string import numpy diff --git a/ciphers/permutation_cipher.py b/ciphers/permutation_cipher.py index c3f3fd1f..9e1c64a7 100644 --- a/ciphers/permutation_cipher.py +++ b/ciphers/permutation_cipher.py @@ -7,6 +7,7 @@ determine the order of character rearrangement. For more info: https://www.nku.edu/~christensen/1402%20permutation%20ciphers.pdf """ + import random diff --git a/ciphers/rail_fence_cipher.py b/ciphers/rail_fence_cipher.py index 47ee7db8..5b2311a1 100644 --- a/ciphers/rail_fence_cipher.py +++ b/ciphers/rail_fence_cipher.py @@ -1,4 +1,4 @@ -""" https://en.wikipedia.org/wiki/Rail_fence_cipher """ +"""https://en.wikipedia.org/wiki/Rail_fence_cipher""" def encrypt(input_string: str, key: int) -> str: diff --git a/ciphers/rsa_factorization.py b/ciphers/rsa_factorization.py index 9ee52777..0a358a4f 100644 --- a/ciphers/rsa_factorization.py +++ b/ciphers/rsa_factorization.py @@ -7,6 +7,7 @@ Source: on page 3 of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html large number can take minutes to factor, therefore are not included in doctest. """ + from __future__ import annotations import math diff --git a/ciphers/xor_cipher.py b/ciphers/xor_cipher.py index e30955d4..24d88a0f 100644 --- a/ciphers/xor_cipher.py +++ b/ciphers/xor_cipher.py @@ -1,21 +1,22 @@ """ - author: Christian Bender - date: 21.12.2017 - class: XORCipher +author: Christian Bender +date: 21.12.2017 +class: XORCipher - This class implements the XOR-cipher algorithm and provides - some useful methods for encrypting and decrypting strings and - files. +This class implements the XOR-cipher algorithm and provides +some useful methods for encrypting and decrypting strings and +files. - Overview about methods +Overview about methods - - encrypt : list of char - - decrypt : list of char - - encrypt_string : str - - decrypt_string : str - - encrypt_file : boolean - - decrypt_file : boolean +- encrypt : list of char +- decrypt : list of char +- encrypt_string : str +- decrypt_string : str +- encrypt_file : boolean +- decrypt_file : boolean """ + from __future__ import annotations diff --git a/compression/burrows_wheeler.py b/compression/burrows_wheeler.py index 52bb045d..ce493a70 100644 --- a/compression/burrows_wheeler.py +++ b/compression/burrows_wheeler.py @@ -10,6 +10,7 @@ without needing to store any additional data except the position of the first original character. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. """ + from __future__ import annotations from typing import TypedDict diff --git a/compression/lempel_ziv.py b/compression/lempel_ziv.py index ea6f3394..ac3f0c6c 100644 --- a/compression/lempel_ziv.py +++ b/compression/lempel_ziv.py @@ -1,6 +1,6 @@ """ - One of the several implementations of Lempel–Ziv–Welch compression algorithm - https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch +One of the several implementations of Lempel–Ziv–Welch compression algorithm +https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math diff --git a/compression/lempel_ziv_decompress.py b/compression/lempel_ziv_decompress.py index ddedc3d6..0e49c83f 100644 --- a/compression/lempel_ziv_decompress.py +++ b/compression/lempel_ziv_decompress.py @@ -1,6 +1,6 @@ """ - One of the several implementations of Lempel–Ziv–Welch decompression algorithm - https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch +One of the several implementations of Lempel–Ziv–Welch decompression algorithm +https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math diff --git a/compression/lz77.py b/compression/lz77.py index 1b201c59..09b8b021 100644 --- a/compression/lz77.py +++ b/compression/lz77.py @@ -28,7 +28,6 @@ Sources: en.wikipedia.org/wiki/LZ77_and_LZ78 """ - from dataclasses import dataclass __version__ = "0.1" diff --git a/computer_vision/haralick_descriptors.py b/computer_vision/haralick_descriptors.py index 007421e3..712bd496 100644 --- a/computer_vision/haralick_descriptors.py +++ b/computer_vision/haralick_descriptors.py @@ -2,6 +2,7 @@ https://en.wikipedia.org/wiki/Image_texture https://en.wikipedia.org/wiki/Co-occurrence_matrix#Application_to_image_analysis """ + import imageio.v2 as imageio import numpy as np diff --git a/computer_vision/horn_schunck.py b/computer_vision/horn_schunck.py index b63e0268..f33b5b1c 100644 --- a/computer_vision/horn_schunck.py +++ b/computer_vision/horn_schunck.py @@ -1,12 +1,12 @@ """ - The Horn-Schunck method estimates the optical flow for every single pixel of - a sequence of images. - It works by assuming brightness constancy between two consecutive frames - and smoothness in the optical flow. +The Horn-Schunck method estimates the optical flow for every single pixel of +a sequence of images. +It works by assuming brightness constancy between two consecutive frames +and smoothness in the optical flow. - Useful resources: - Wikipedia: https://en.wikipedia.org/wiki/Horn%E2%80%93Schunck_method - Paper: http://image.diku.dk/imagecanon/material/HornSchunckOptical_Flow.pdf +Useful resources: +Wikipedia: https://en.wikipedia.org/wiki/Horn%E2%80%93Schunck_method +Paper: http://image.diku.dk/imagecanon/material/HornSchunckOptical_Flow.pdf """ from typing import SupportsIndex diff --git a/conversions/decimal_to_hexadecimal.py b/conversions/decimal_to_hexadecimal.py index b1fb4f08..ee79592d 100644 --- a/conversions/decimal_to_hexadecimal.py +++ b/conversions/decimal_to_hexadecimal.py @@ -1,4 +1,4 @@ -""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """ +"""Convert Base 10 (Decimal) Values to Hexadecimal Representations""" # set decimal value for each hexadecimal digit values = { diff --git a/conversions/prefix_conversions.py b/conversions/prefix_conversions.py index 06b759e3..714677f3 100644 --- a/conversions/prefix_conversions.py +++ b/conversions/prefix_conversions.py @@ -1,6 +1,7 @@ """ Convert International System of Units (SI) and Binary prefixes """ + from __future__ import annotations from enum import Enum diff --git a/conversions/temperature_conversions.py b/conversions/temperature_conversions.py index f7af6c8f..dde1d2f0 100644 --- a/conversions/temperature_conversions.py +++ b/conversions/temperature_conversions.py @@ -1,4 +1,4 @@ -""" Convert between different units of temperature """ +"""Convert between different units of temperature""" def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: diff --git a/data_structures/arrays/pairs_with_given_sum.py b/data_structures/arrays/pairs_with_given_sum.py index c4a5ceea..b27bd78e 100644 --- a/data_structures/arrays/pairs_with_given_sum.py +++ b/data_structures/arrays/pairs_with_given_sum.py @@ -6,6 +6,7 @@ elements whose sum is equal to req_sum. https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/0 """ + from itertools import combinations diff --git a/data_structures/arrays/sparse_table.py b/data_structures/arrays/sparse_table.py index a15d5649..4606fe90 100644 --- a/data_structures/arrays/sparse_table.py +++ b/data_structures/arrays/sparse_table.py @@ -1,15 +1,16 @@ """ - Sparse table is a data structure that allows answering range queries on - a static number list, i.e. the elements do not change throughout all the queries. +Sparse table is a data structure that allows answering range queries on +a static number list, i.e. the elements do not change throughout all the queries. - The implementation below will solve the problem of Range Minimum Query: - Finding the minimum value of a subset [L..R] of a static number list. +The implementation below will solve the problem of Range Minimum Query: +Finding the minimum value of a subset [L..R] of a static number list. - Overall time complexity: O(nlogn) - Overall space complexity: O(nlogn) +Overall time complexity: O(nlogn) +Overall space complexity: O(nlogn) - Wikipedia link: https://en.wikipedia.org/wiki/Range_minimum_query +Wikipedia link: https://en.wikipedia.org/wiki/Range_minimum_query """ + from math import log2 diff --git a/data_structures/arrays/sudoku_solver.py b/data_structures/arrays/sudoku_solver.py index 20ac32e3..c9dffcde 100644 --- a/data_structures/arrays/sudoku_solver.py +++ b/data_structures/arrays/sudoku_solver.py @@ -3,6 +3,7 @@ Please do not modify this file! It is published at https://norvig.com/sudoku.ht only minimal changes to work with modern versions of Python. If you have improvements, please make them in a separate file. """ + import random import time diff --git a/data_structures/binary_tree/avl_tree.py b/data_structures/binary_tree/avl_tree.py index 4c1fb17a..041ed7e3 100644 --- a/data_structures/binary_tree/avl_tree.py +++ b/data_structures/binary_tree/avl_tree.py @@ -5,6 +5,7 @@ python3 -m doctest -v avl_tree.py For testing run: python avl_tree.py """ + from __future__ import annotations import math diff --git a/data_structures/binary_tree/binary_search_tree.py b/data_structures/binary_tree/binary_search_tree.py index 9071f03d..08a60a12 100644 --- a/data_structures/binary_tree/binary_search_tree.py +++ b/data_structures/binary_tree/binary_search_tree.py @@ -88,6 +88,7 @@ True >>> not t True """ + from __future__ import annotations from collections.abc import Iterable, Iterator diff --git a/data_structures/binary_tree/binary_search_tree_recursive.py b/data_structures/binary_tree/binary_search_tree_recursive.py index 13b9b392..6af1b053 100644 --- a/data_structures/binary_tree/binary_search_tree_recursive.py +++ b/data_structures/binary_tree/binary_search_tree_recursive.py @@ -7,6 +7,7 @@ python -m unittest binary_search_tree_recursive.py To run an example: python binary_search_tree_recursive.py """ + from __future__ import annotations import unittest diff --git a/data_structures/binary_tree/binary_tree_node_sum.py b/data_structures/binary_tree/binary_tree_node_sum.py index 5a13e74e..066617b6 100644 --- a/data_structures/binary_tree/binary_tree_node_sum.py +++ b/data_structures/binary_tree/binary_tree_node_sum.py @@ -8,7 +8,6 @@ Python implementation: frames that could be in memory is `n` """ - from __future__ import annotations from collections.abc import Iterator diff --git a/data_structures/binary_tree/diameter_of_binary_tree.py b/data_structures/binary_tree/diameter_of_binary_tree.py index bbe70b02..75e5e737 100644 --- a/data_structures/binary_tree/diameter_of_binary_tree.py +++ b/data_structures/binary_tree/diameter_of_binary_tree.py @@ -2,6 +2,7 @@ The diameter/width of a tree is defined as the number of nodes on the longest path between two end nodes. """ + from __future__ import annotations from dataclasses import dataclass diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 8820a509..9b2c7b9a 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -10,6 +10,7 @@ https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list Author: Arunkumar A Date: 04/09/2023 """ + from __future__ import annotations diff --git a/data_structures/binary_tree/floor_and_ceiling.py b/data_structures/binary_tree/floor_and_ceiling.py index f8a1adbd..b464aefa 100644 --- a/data_structures/binary_tree/floor_and_ceiling.py +++ b/data_structures/binary_tree/floor_and_ceiling.py @@ -9,6 +9,7 @@ https://bit.ly/46uB0a2 Author : Arunkumar Date : 14th October 2023 """ + from __future__ import annotations from collections.abc import Iterator diff --git a/data_structures/binary_tree/is_sorted.py b/data_structures/binary_tree/is_sorted.py index 5876c5a9..509a4266 100644 --- a/data_structures/binary_tree/is_sorted.py +++ b/data_structures/binary_tree/is_sorted.py @@ -13,6 +13,7 @@ If n is the number of nodes in the tree then: Runtime: O(n) Space: O(1) """ + from __future__ import annotations from collections.abc import Iterator diff --git a/data_structures/binary_tree/is_sum_tree.py b/data_structures/binary_tree/is_sum_tree.py index 3f9cf1d5..846bea0f 100644 --- a/data_structures/binary_tree/is_sum_tree.py +++ b/data_structures/binary_tree/is_sum_tree.py @@ -3,6 +3,7 @@ Is a binary tree a sum tree where the value of every non-leaf node is equal to t of the values of its left and right subtrees? https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree """ + from __future__ import annotations from collections.abc import Iterator diff --git a/data_structures/binary_tree/merge_two_binary_trees.py b/data_structures/binary_tree/merge_two_binary_trees.py index 3380f8c5..6bbb3042 100644 --- a/data_structures/binary_tree/merge_two_binary_trees.py +++ b/data_structures/binary_tree/merge_two_binary_trees.py @@ -5,6 +5,7 @@ The rule for merging is that if two nodes overlap, then put the value sum of both nodes to the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. """ + from __future__ import annotations diff --git a/data_structures/binary_tree/mirror_binary_tree.py b/data_structures/binary_tree/mirror_binary_tree.py index 39305c2a..62e2f08d 100644 --- a/data_structures/binary_tree/mirror_binary_tree.py +++ b/data_structures/binary_tree/mirror_binary_tree.py @@ -3,6 +3,7 @@ Given the root of a binary tree, mirror the tree, and return its root. Leetcode problem reference: https://leetcode.com/problems/mirror-binary-tree/ """ + from __future__ import annotations from collections.abc import Iterator diff --git a/data_structures/binary_tree/non_recursive_segment_tree.py b/data_structures/binary_tree/non_recursive_segment_tree.py index 04164e5c..42c78a3a 100644 --- a/data_structures/binary_tree/non_recursive_segment_tree.py +++ b/data_structures/binary_tree/non_recursive_segment_tree.py @@ -35,6 +35,7 @@ https://www.geeksforgeeks.org/segment-tree-efficient-implementation/ >>> st.query(0, 2) [1, 2, 3] """ + from __future__ import annotations from collections.abc import Callable diff --git a/data_structures/binary_tree/number_of_possible_binary_trees.py b/data_structures/binary_tree/number_of_possible_binary_trees.py index 684c518b..1c3dff37 100644 --- a/data_structures/binary_tree/number_of_possible_binary_trees.py +++ b/data_structures/binary_tree/number_of_possible_binary_trees.py @@ -6,6 +6,7 @@ We will use the formula: t(n) = SUMMATION(i = 1 to n)t(i-1)t(n-i) Further details at Wikipedia: https://en.wikipedia.org/wiki/Catalan_number """ + """ Our Contribution: Basically we Create the 2 function: diff --git a/data_structures/binary_tree/red_black_tree.py b/data_structures/binary_tree/red_black_tree.py index fc299301..3b5845cd 100644 --- a/data_structures/binary_tree/red_black_tree.py +++ b/data_structures/binary_tree/red_black_tree.py @@ -2,6 +2,7 @@ psf/black : true ruff : passed """ + from __future__ import annotations from collections.abc import Iterator diff --git a/data_structures/binary_tree/segment_tree_other.py b/data_structures/binary_tree/segment_tree_other.py index cc77c495..95f21ddd 100644 --- a/data_structures/binary_tree/segment_tree_other.py +++ b/data_structures/binary_tree/segment_tree_other.py @@ -3,6 +3,7 @@ Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ + from collections.abc import Sequence from queue import Queue diff --git a/data_structures/binary_tree/symmetric_tree.py b/data_structures/binary_tree/symmetric_tree.py index 331a2584..98a766ca 100644 --- a/data_structures/binary_tree/symmetric_tree.py +++ b/data_structures/binary_tree/symmetric_tree.py @@ -4,6 +4,7 @@ Given the root of a binary tree, check whether it is a mirror of itself Leetcode reference: https://leetcode.com/problems/symmetric-tree/ """ + from __future__ import annotations from dataclasses import dataclass diff --git a/data_structures/binary_tree/wavelet_tree.py b/data_structures/binary_tree/wavelet_tree.py index 041e140f..2da571e8 100644 --- a/data_structures/binary_tree/wavelet_tree.py +++ b/data_structures/binary_tree/wavelet_tree.py @@ -7,6 +7,7 @@ such as the with segment trees or fenwick trees. You can read more about them he 2. https://www.youtube.com/watch?v=4aSv9PcecDw&t=811s 3. https://www.youtube.com/watch?v=CybAgVF-MMc&t=1178s """ + from __future__ import annotations test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7] diff --git a/data_structures/disjoint_set/disjoint_set.py b/data_structures/disjoint_set/disjoint_set.py index 12dafb2d..edc4736b 100644 --- a/data_structures/disjoint_set/disjoint_set.py +++ b/data_structures/disjoint_set/disjoint_set.py @@ -1,6 +1,6 @@ """ - Disjoint set. - Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure +Disjoint set. +Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure """ diff --git a/data_structures/hashing/bloom_filter.py b/data_structures/hashing/bloom_filter.py index 7fd0985b..eb2cb4b7 100644 --- a/data_structures/hashing/bloom_filter.py +++ b/data_structures/hashing/bloom_filter.py @@ -58,6 +58,7 @@ The probability decreases with the number of bits in the bitarray. >>> bloom.bitstring '01100101' """ + from hashlib import md5, sha256 HASH_FUNCTIONS = (sha256, md5) diff --git a/data_structures/hashing/double_hash.py b/data_structures/hashing/double_hash.py index 76c6c868..324282cb 100644 --- a/data_structures/hashing/double_hash.py +++ b/data_structures/hashing/double_hash.py @@ -11,6 +11,7 @@ Where hash1() and hash2() are hash functions and TABLE_SIZE is size of hash tabl Reference: https://en.wikipedia.org/wiki/Double_hashing """ + from .hash_table import HashTable from .number_theory.prime_numbers import is_prime, next_prime diff --git a/data_structures/hashing/hash_map.py b/data_structures/hashing/hash_map.py index 6a6f8e54..9213d693 100644 --- a/data_structures/hashing/hash_map.py +++ b/data_structures/hashing/hash_map.py @@ -7,6 +7,7 @@ Another hash map implementation, with a good explanation. Modern Dictionaries by Raymond Hettinger https://www.youtube.com/watch?v=p33CVV29OG8 """ + from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar diff --git a/data_structures/hashing/number_theory/prime_numbers.py b/data_structures/hashing/number_theory/prime_numbers.py index 0c25896f..2549a147 100644 --- a/data_structures/hashing/number_theory/prime_numbers.py +++ b/data_structures/hashing/number_theory/prime_numbers.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """ - module to operations with prime numbers +module to operations with prime numbers """ import math diff --git a/data_structures/linked_list/__init__.py b/data_structures/linked_list/__init__.py index 225113f7..00ef337a 100644 --- a/data_structures/linked_list/__init__.py +++ b/data_structures/linked_list/__init__.py @@ -5,6 +5,7 @@ Nodes contain data and also may link to other nodes: head node gives us access of the complete list - Last node: points to null """ + from __future__ import annotations from typing import Any diff --git a/data_structures/linked_list/merge_two_lists.py b/data_structures/linked_list/merge_two_lists.py index ca0d3bb4..e47dbdad 100644 --- a/data_structures/linked_list/merge_two_lists.py +++ b/data_structures/linked_list/merge_two_lists.py @@ -1,6 +1,7 @@ """ Algorithm that merges two sorted linked lists into one sorted linked list. """ + from __future__ import annotations from collections.abc import Iterable, Iterator diff --git a/data_structures/linked_list/skip_list.py b/data_structures/linked_list/skip_list.py index 4413c53e..88d3e0da 100644 --- a/data_structures/linked_list/skip_list.py +++ b/data_structures/linked_list/skip_list.py @@ -2,6 +2,7 @@ Based on "Skip Lists: A Probabilistic Alternative to Balanced Trees" by William Pugh https://epaperpress.com/sortsearch/download/skiplist.pdf """ + from __future__ import annotations from random import random diff --git a/data_structures/queue/double_ended_queue.py b/data_structures/queue/double_ended_queue.py index 17a23038..607d0bda 100644 --- a/data_structures/queue/double_ended_queue.py +++ b/data_structures/queue/double_ended_queue.py @@ -1,6 +1,7 @@ """ Implementation of double ended queue. """ + from __future__ import annotations from collections.abc import Iterable diff --git a/data_structures/queue/linked_queue.py b/data_structures/queue/linked_queue.py index 3af97d28..80f6d309 100644 --- a/data_structures/queue/linked_queue.py +++ b/data_structures/queue/linked_queue.py @@ -1,4 +1,5 @@ -""" A Queue using a linked list like structure """ +"""A Queue using a linked list like structure""" + from __future__ import annotations from collections.abc import Iterator diff --git a/data_structures/queue/queue_on_pseudo_stack.py b/data_structures/queue/queue_on_pseudo_stack.py index d9845100..2da67ecc 100644 --- a/data_structures/queue/queue_on_pseudo_stack.py +++ b/data_structures/queue/queue_on_pseudo_stack.py @@ -1,4 +1,5 @@ """Queue represented by a pseudo stack (represented by a list with pop and append)""" + from typing import Any diff --git a/data_structures/stacks/dijkstras_two_stack_algorithm.py b/data_structures/stacks/dijkstras_two_stack_algorithm.py index 976c9a53..94d19156 100644 --- a/data_structures/stacks/dijkstras_two_stack_algorithm.py +++ b/data_structures/stacks/dijkstras_two_stack_algorithm.py @@ -29,6 +29,7 @@ RULE 5: When the entire infix expression has been scanned, the value left on NOTE: It only works with whole numbers. """ + __author__ = "Alexander Joslin" import operator as op diff --git a/data_structures/stacks/stack_with_singly_linked_list.py b/data_structures/stacks/stack_with_singly_linked_list.py index f5ce83b8..8e77c2b9 100644 --- a/data_structures/stacks/stack_with_singly_linked_list.py +++ b/data_structures/stacks/stack_with_singly_linked_list.py @@ -1,4 +1,5 @@ -""" A Stack using a linked list like structure """ +"""A Stack using a linked list like structure""" + from __future__ import annotations from collections.abc import Iterator diff --git a/digital_image_processing/convert_to_negative.py b/digital_image_processing/convert_to_negative.py index 7df44138..9bf2d8f2 100644 --- a/digital_image_processing/convert_to_negative.py +++ b/digital_image_processing/convert_to_negative.py @@ -1,6 +1,7 @@ """ - Implemented an algorithm using opencv to convert a colored image into its negative +Implemented an algorithm using opencv to convert a colored image into its negative """ + from cv2 import destroyAllWindows, imread, imshow, waitKey diff --git a/digital_image_processing/dithering/burkes.py b/digital_image_processing/dithering/burkes.py index 35aedc16..4b59356d 100644 --- a/digital_image_processing/dithering/burkes.py +++ b/digital_image_processing/dithering/burkes.py @@ -1,6 +1,7 @@ """ Implementation Burke's algorithm (dithering) """ + import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey diff --git a/digital_image_processing/filters/bilateral_filter.py b/digital_image_processing/filters/bilateral_filter.py index 199ac4d9..6ef4434d 100644 --- a/digital_image_processing/filters/bilateral_filter.py +++ b/digital_image_processing/filters/bilateral_filter.py @@ -9,6 +9,7 @@ Inputs: Output: img:A 2d zero padded image with values in between 0 and 1 """ + import math import sys diff --git a/digital_image_processing/filters/gaussian_filter.py b/digital_image_processing/filters/gaussian_filter.py index 634d836e..0c34e59f 100644 --- a/digital_image_processing/filters/gaussian_filter.py +++ b/digital_image_processing/filters/gaussian_filter.py @@ -1,6 +1,7 @@ """ Implementation of gaussian filter algorithm """ + from itertools import product from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey diff --git a/digital_image_processing/filters/median_filter.py b/digital_image_processing/filters/median_filter.py index 17401856..fc8b582e 100644 --- a/digital_image_processing/filters/median_filter.py +++ b/digital_image_processing/filters/median_filter.py @@ -1,6 +1,7 @@ """ Implementation of median filter algorithm """ + from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like diff --git a/digital_image_processing/histogram_equalization/histogram_stretch.py b/digital_image_processing/histogram_equalization/histogram_stretch.py index 5ea7773e..1270c964 100644 --- a/digital_image_processing/histogram_equalization/histogram_stretch.py +++ b/digital_image_processing/histogram_equalization/histogram_stretch.py @@ -3,6 +3,7 @@ Created on Fri Sep 28 15:22:29 2018 @author: Binish125 """ + import copy import os diff --git a/digital_image_processing/resize/resize.py b/digital_image_processing/resize/resize.py index 4836521f..7bde118d 100644 --- a/digital_image_processing/resize/resize.py +++ b/digital_image_processing/resize/resize.py @@ -1,4 +1,5 @@ -""" Multiple image resizing techniques """ +"""Multiple image resizing techniques""" + import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey diff --git a/digital_image_processing/sepia.py b/digital_image_processing/sepia.py index e9dd2c06..1924a804 100644 --- a/digital_image_processing/sepia.py +++ b/digital_image_processing/sepia.py @@ -1,6 +1,7 @@ """ - Implemented an algorithm using opencv to tone an image with sepia technique +Implemented an algorithm using opencv to tone an image with sepia technique """ + from cv2 import destroyAllWindows, imread, imshow, waitKey diff --git a/digital_image_processing/test_digital_image_processing.py b/digital_image_processing/test_digital_image_processing.py index 7993110d..d1200f4d 100644 --- a/digital_image_processing/test_digital_image_processing.py +++ b/digital_image_processing/test_digital_image_processing.py @@ -1,6 +1,7 @@ """ PyTest's for Digital Image Processing """ + import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uint8 diff --git a/divide_and_conquer/convex_hull.py b/divide_and_conquer/convex_hull.py index 1d1bf301..a5d8b713 100644 --- a/divide_and_conquer/convex_hull.py +++ b/divide_and_conquer/convex_hull.py @@ -12,6 +12,7 @@ There are other several other algorithms for the convex hull problem which have not been implemented here, yet. """ + from __future__ import annotations from collections.abc import Iterable diff --git a/divide_and_conquer/kth_order_statistic.py b/divide_and_conquer/kth_order_statistic.py index 666ad1a3..23fd8be5 100644 --- a/divide_and_conquer/kth_order_statistic.py +++ b/divide_and_conquer/kth_order_statistic.py @@ -8,6 +8,7 @@ This is a divide and conquer algorithm that can find a solution in O(n) time. For more information of this algorithm: https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf """ + from __future__ import annotations from random import choice diff --git a/divide_and_conquer/max_subarray.py b/divide_and_conquer/max_subarray.py index 851ef621..0fad7ab5 100644 --- a/divide_and_conquer/max_subarray.py +++ b/divide_and_conquer/max_subarray.py @@ -6,6 +6,7 @@ maximum sum within a given array of numbers. For example, given the array This divide-and-conquer algorithm finds the maximum subarray in O(n log n) time. """ + from __future__ import annotations import time diff --git a/divide_and_conquer/peak.py b/divide_and_conquer/peak.py index e60f28bf..71ab5ac8 100644 --- a/divide_and_conquer/peak.py +++ b/divide_and_conquer/peak.py @@ -7,6 +7,7 @@ to find the maximum of the array. (From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1) """ + from __future__ import annotations diff --git a/dynamic_programming/all_construct.py b/dynamic_programming/all_construct.py index 6e53a702..5d585fc7 100644 --- a/dynamic_programming/all_construct.py +++ b/dynamic_programming/all_construct.py @@ -2,6 +2,7 @@ Program to list all the ways a target string can be constructed from the given list of substrings """ + from __future__ import annotations diff --git a/dynamic_programming/bitmask.py b/dynamic_programming/bitmask.py index 56bb8e96..a6e6a0cd 100644 --- a/dynamic_programming/bitmask.py +++ b/dynamic_programming/bitmask.py @@ -8,6 +8,7 @@ We have N tasks and M people. Each person in M can do only certain of these task a person can do only one task and a task is performed only by one person. Find the total no of ways in which the tasks can be distributed. """ + from collections import defaultdict diff --git a/dynamic_programming/fast_fibonacci.py b/dynamic_programming/fast_fibonacci.py index f48186a3..9f956ca2 100644 --- a/dynamic_programming/fast_fibonacci.py +++ b/dynamic_programming/fast_fibonacci.py @@ -4,6 +4,7 @@ This program calculates the nth Fibonacci number in O(log(n)). It's possible to calculate F(1_000_000) in less than a second. """ + from __future__ import annotations import sys diff --git a/dynamic_programming/iterating_through_submasks.py b/dynamic_programming/iterating_through_submasks.py index 4d0a250e..372dd2c7 100644 --- a/dynamic_programming/iterating_through_submasks.py +++ b/dynamic_programming/iterating_through_submasks.py @@ -5,6 +5,7 @@ You are given a bitmask m and you want to efficiently iterate through all of its submasks. The mask s is submask of m if only bits that were included in bitmask are set """ + from __future__ import annotations diff --git a/dynamic_programming/longest_increasing_subsequence.py b/dynamic_programming/longest_increasing_subsequence.py index d8278937..2a78e2e7 100644 --- a/dynamic_programming/longest_increasing_subsequence.py +++ b/dynamic_programming/longest_increasing_subsequence.py @@ -10,6 +10,7 @@ return it. Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output """ + from __future__ import annotations diff --git a/dynamic_programming/matrix_chain_multiplication.py b/dynamic_programming/matrix_chain_multiplication.py index 084254a6..da6e525c 100644 --- a/dynamic_programming/matrix_chain_multiplication.py +++ b/dynamic_programming/matrix_chain_multiplication.py @@ -38,6 +38,7 @@ Example input: arr = [40, 20, 30, 10, 30] output: 26000 """ + from collections.abc import Iterator from contextlib import contextmanager from functools import cache diff --git a/dynamic_programming/max_subarray_sum.py b/dynamic_programming/max_subarray_sum.py index c7694347..8c1dc088 100644 --- a/dynamic_programming/max_subarray_sum.py +++ b/dynamic_programming/max_subarray_sum.py @@ -9,6 +9,7 @@ subarray sum problem in O(n) time and O(1) space. Reference: https://en.wikipedia.org/wiki/Maximum_subarray_problem """ + from collections.abc import Sequence diff --git a/electronics/charging_capacitor.py b/electronics/charging_capacitor.py index 4029b0ec..0021e4e3 100644 --- a/electronics/charging_capacitor.py +++ b/electronics/charging_capacitor.py @@ -14,6 +14,7 @@ represented as τ (tau). By using this RC-timeconstant we can find the voltage time 't' from the initiation of charging a capacitor with the help of the exponential function containing RC. Both at charging and discharging of a capacitor. """ + from math import exp # value of exp = 2.718281828459… diff --git a/electronics/charging_inductor.py b/electronics/charging_inductor.py index e5c0126c..8a3bbc0b 100644 --- a/electronics/charging_inductor.py +++ b/electronics/charging_inductor.py @@ -25,6 +25,7 @@ when inductor is connected across 'AC' potential source. It starts to store the in its 'magnetic field'.with the help 'RL-time-constant' we can find current at any time in inductor while it is charging. """ + from math import exp # value of exp = 2.718281828459… diff --git a/electronics/resistor_color_code.py b/electronics/resistor_color_code.py index b0534b81..189d1994 100644 --- a/electronics/resistor_color_code.py +++ b/electronics/resistor_color_code.py @@ -58,6 +58,7 @@ Sources : https://learn.parallax.com/support/reference/resistor-color-codes https://byjus.com/physics/resistor-colour-codes/ """ + valid_colors: list = [ "Black", "Brown", diff --git a/financial/exponential_moving_average.py b/financial/exponential_moving_average.py index 0b6cea3b..b56eb271 100644 --- a/financial/exponential_moving_average.py +++ b/financial/exponential_moving_average.py @@ -1,12 +1,12 @@ """ - Calculate the exponential moving average (EMA) on the series of stock prices. - Wikipedia Reference: https://en.wikipedia.org/wiki/Exponential_smoothing - https://www.investopedia.com/terms/e/ema.asp#toc-what-is-an-exponential - -moving-average-ema +Calculate the exponential moving average (EMA) on the series of stock prices. +Wikipedia Reference: https://en.wikipedia.org/wiki/Exponential_smoothing +https://www.investopedia.com/terms/e/ema.asp#toc-what-is-an-exponential +-moving-average-ema - Exponential moving average is used in finance to analyze changes stock prices. - EMA is used in conjunction with Simple moving average (SMA), EMA reacts to the - changes in the value quicker than SMA, which is one of the advantages of using EMA. +Exponential moving average is used in finance to analyze changes stock prices. +EMA is used in conjunction with Simple moving average (SMA), EMA reacts to the +changes in the value quicker than SMA, which is one of the advantages of using EMA. """ from collections.abc import Iterator diff --git a/financial/simple_moving_average.py b/financial/simple_moving_average.py index d5d68ffd..f5ae444f 100644 --- a/financial/simple_moving_average.py +++ b/financial/simple_moving_average.py @@ -6,6 +6,7 @@ and identify trends. Reference: https://en.wikipedia.org/wiki/Moving_average """ + from collections.abc import Sequence diff --git a/fractals/koch_snowflake.py b/fractals/koch_snowflake.py index b0aaa86b..30cd4b39 100644 --- a/fractals/koch_snowflake.py +++ b/fractals/koch_snowflake.py @@ -20,7 +20,6 @@ Requirements (pip): - numpy """ - from __future__ import annotations import matplotlib.pyplot as plt # type: ignore diff --git a/fractals/mandelbrot.py b/fractals/mandelbrot.py index 84dbda99..5eb9af0a 100644 --- a/fractals/mandelbrot.py +++ b/fractals/mandelbrot.py @@ -15,7 +15,6 @@ the boundary of the Mandelbrot set a fractal curve. (see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set ) """ - import colorsys from PIL import Image # type: ignore diff --git a/fractals/sierpinski_triangle.py b/fractals/sierpinski_triangle.py index 45f7ab84..ceb2001b 100644 --- a/fractals/sierpinski_triangle.py +++ b/fractals/sierpinski_triangle.py @@ -22,6 +22,7 @@ Credits: This code was written by editing the code from https://www.riannetrujillo.com/blog/python-fractal/ """ + import sys import turtle diff --git a/graphs/bi_directional_dijkstra.py b/graphs/bi_directional_dijkstra.py index 529a235d..7b9eac6c 100644 --- a/graphs/bi_directional_dijkstra.py +++ b/graphs/bi_directional_dijkstra.py @@ -10,7 +10,6 @@ Reference: shorturl.at/exHM7 # Author: Swayam Singh (https://github.com/practice404) - from queue import PriorityQueue from typing import Any diff --git a/graphs/bidirectional_a_star.py b/graphs/bidirectional_a_star.py index 373d6714..00f623de 100644 --- a/graphs/bidirectional_a_star.py +++ b/graphs/bidirectional_a_star.py @@ -1,6 +1,7 @@ """ https://en.wikipedia.org/wiki/Bidirectional_search """ + from __future__ import annotations import time diff --git a/graphs/bidirectional_breadth_first_search.py b/graphs/bidirectional_breadth_first_search.py index 511b080a..71c5a9af 100644 --- a/graphs/bidirectional_breadth_first_search.py +++ b/graphs/bidirectional_breadth_first_search.py @@ -1,6 +1,7 @@ """ https://en.wikipedia.org/wiki/Bidirectional_search """ + from __future__ import annotations import time diff --git a/graphs/boruvka.py b/graphs/boruvka.py index 2715a308..3dc059ff 100644 --- a/graphs/boruvka.py +++ b/graphs/boruvka.py @@ -1,29 +1,30 @@ """Borůvka's algorithm. - Determines the minimum spanning tree (MST) of a graph using the Borůvka's algorithm. - Borůvka's algorithm is a greedy algorithm for finding a minimum spanning tree in a - connected graph, or a minimum spanning forest if a graph that is not connected. +Determines the minimum spanning tree (MST) of a graph using the Borůvka's algorithm. +Borůvka's algorithm is a greedy algorithm for finding a minimum spanning tree in a +connected graph, or a minimum spanning forest if a graph that is not connected. - The time complexity of this algorithm is O(ELogV), where E represents the number - of edges, while V represents the number of nodes. - O(number_of_edges Log number_of_nodes) +The time complexity of this algorithm is O(ELogV), where E represents the number +of edges, while V represents the number of nodes. +O(number_of_edges Log number_of_nodes) - The space complexity of this algorithm is O(V + E), since we have to keep a couple - of lists whose sizes are equal to the number of nodes, as well as keep all the - edges of a graph inside of the data structure itself. +The space complexity of this algorithm is O(V + E), since we have to keep a couple +of lists whose sizes are equal to the number of nodes, as well as keep all the +edges of a graph inside of the data structure itself. - Borůvka's algorithm gives us pretty much the same result as other MST Algorithms - - they all find the minimum spanning tree, and the time complexity is approximately - the same. +Borůvka's algorithm gives us pretty much the same result as other MST Algorithms - +they all find the minimum spanning tree, and the time complexity is approximately +the same. - One advantage that Borůvka's algorithm has compared to the alternatives is that it - doesn't need to presort the edges or maintain a priority queue in order to find the - minimum spanning tree. - Even though that doesn't help its complexity, since it still passes the edges logE - times, it is a bit simpler to code. +One advantage that Borůvka's algorithm has compared to the alternatives is that it +doesn't need to presort the edges or maintain a priority queue in order to find the +minimum spanning tree. +Even though that doesn't help its complexity, since it still passes the edges logE +times, it is a bit simpler to code. - Details: https://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithm +Details: https://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithm """ + from __future__ import annotations from typing import Any diff --git a/graphs/breadth_first_search.py b/graphs/breadth_first_search.py index 171d3875..cab79be3 100644 --- a/graphs/breadth_first_search.py +++ b/graphs/breadth_first_search.py @@ -1,6 +1,7 @@ #!/usr/bin/python -""" Author: OMKAR PATHAK """ +"""Author: OMKAR PATHAK""" + from __future__ import annotations from queue import Queue diff --git a/graphs/breadth_first_search_2.py b/graphs/breadth_first_search_2.py index a0b92b90..ccadfa34 100644 --- a/graphs/breadth_first_search_2.py +++ b/graphs/breadth_first_search_2.py @@ -12,6 +12,7 @@ while Q is non-empty: mark w as explored add w to Q (at the end) """ + from __future__ import annotations from collections import deque diff --git a/graphs/breadth_first_search_shortest_path.py b/graphs/breadth_first_search_shortest_path.py index d489b110..c06440bc 100644 --- a/graphs/breadth_first_search_shortest_path.py +++ b/graphs/breadth_first_search_shortest_path.py @@ -1,6 +1,7 @@ """Breath First Search (BFS) can be used when finding the shortest path from a given source node to a target node in an unweighted graph. """ + from __future__ import annotations graph = { diff --git a/graphs/breadth_first_search_shortest_path_2.py b/graphs/breadth_first_search_shortest_path_2.py index b0c8d353..4f9b6e65 100644 --- a/graphs/breadth_first_search_shortest_path_2.py +++ b/graphs/breadth_first_search_shortest_path_2.py @@ -1,9 +1,10 @@ """Breadth-first search shortest path implementations. - doctest: - python -m doctest -v bfs_shortest_path.py - Manual test: - python bfs_shortest_path.py +doctest: +python -m doctest -v bfs_shortest_path.py +Manual test: +python bfs_shortest_path.py """ + demo_graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], diff --git a/graphs/breadth_first_search_zero_one_shortest_path.py b/graphs/breadth_first_search_zero_one_shortest_path.py index 78047c5d..d3a255ba 100644 --- a/graphs/breadth_first_search_zero_one_shortest_path.py +++ b/graphs/breadth_first_search_zero_one_shortest_path.py @@ -3,6 +3,7 @@ Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra 0-1-graph is the weighted graph with the weights equal to 0 or 1. Link: https://codeforces.com/blog/entry/22276 """ + from __future__ import annotations from collections import deque diff --git a/graphs/deep_clone_graph.py b/graphs/deep_clone_graph.py index 55678b4c..18ea99c6 100644 --- a/graphs/deep_clone_graph.py +++ b/graphs/deep_clone_graph.py @@ -9,6 +9,7 @@ Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. """ + from dataclasses import dataclass diff --git a/graphs/depth_first_search.py b/graphs/depth_first_search.py index f20a503c..a666e74c 100644 --- a/graphs/depth_first_search.py +++ b/graphs/depth_first_search.py @@ -1,4 +1,5 @@ """Non recursive implementation of a DFS algorithm.""" + from __future__ import annotations diff --git a/graphs/depth_first_search_2.py b/graphs/depth_first_search_2.py index 5ff13af3..8fe48b7f 100644 --- a/graphs/depth_first_search_2.py +++ b/graphs/depth_first_search_2.py @@ -1,6 +1,6 @@ #!/usr/bin/python -""" Author: OMKAR PATHAK """ +"""Author: OMKAR PATHAK""" class Graph: diff --git a/graphs/dijkstra.py b/graphs/dijkstra.py index b0bdfab6..87e9d223 100644 --- a/graphs/dijkstra.py +++ b/graphs/dijkstra.py @@ -30,6 +30,7 @@ only the distance between previous vertex and current vertex but the entire distance between each vertex that makes up the path from start vertex to target vertex. """ + import heapq diff --git a/graphs/even_tree.py b/graphs/even_tree.py index 92ffb4b2..7d478995 100644 --- a/graphs/even_tree.py +++ b/graphs/even_tree.py @@ -12,6 +12,7 @@ Constraints Note: The tree input will be such that it can always be decomposed into components containing an even number of nodes. """ + # pylint: disable=invalid-name from collections import defaultdict diff --git a/graphs/frequent_pattern_graph_miner.py b/graphs/frequent_pattern_graph_miner.py index 208e57f9..f8da73f3 100644 --- a/graphs/frequent_pattern_graph_miner.py +++ b/graphs/frequent_pattern_graph_miner.py @@ -8,6 +8,7 @@ frequent subgraphs and maximum common subgraphs. URL: https://www.researchgate.net/publication/235255851 """ + # fmt: off edge_array = [ ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'bh-e12', 'cd-e2', 'ce-e4', diff --git a/graphs/graph_adjacency_list.py b/graphs/graph_adjacency_list.py index d0b94f03..abc75311 100644 --- a/graphs/graph_adjacency_list.py +++ b/graphs/graph_adjacency_list.py @@ -15,6 +15,7 @@ Potential Future Ideas: - Make edge weights and vertex values customizable to store whatever the client wants - Support multigraph functionality if the client wants it """ + from __future__ import annotations import random diff --git a/graphs/graph_adjacency_matrix.py b/graphs/graph_adjacency_matrix.py index cdef388d..059a6aa9 100644 --- a/graphs/graph_adjacency_matrix.py +++ b/graphs/graph_adjacency_matrix.py @@ -15,6 +15,7 @@ Potential Future Ideas: - Make edge weights and vertex values customizable to store whatever the client wants - Support multigraph functionality if the client wants it """ + from __future__ import annotations import random diff --git a/graphs/graphs_floyd_warshall.py b/graphs/graphs_floyd_warshall.py index 56cf8b9e..aaed9ac5 100644 --- a/graphs/graphs_floyd_warshall.py +++ b/graphs/graphs_floyd_warshall.py @@ -1,7 +1,7 @@ # floyd_warshall.py """ - The problem is to find the shortest distance between all pairs of vertices in a - weighted directed graph that can have negative edge weights. +The problem is to find the shortest distance between all pairs of vertices in a +weighted directed graph that can have negative edge weights. """ diff --git a/graphs/minimum_spanning_tree_prims2.py b/graphs/minimum_spanning_tree_prims2.py index 81f30ef6..cc918f81 100644 --- a/graphs/minimum_spanning_tree_prims2.py +++ b/graphs/minimum_spanning_tree_prims2.py @@ -6,6 +6,7 @@ edges in the tree is minimized. The algorithm operates by building this tree one at a time, from an arbitrary starting vertex, at each step adding the cheapest possible connection from the tree to another vertex. """ + from __future__ import annotations from sys import maxsize diff --git a/graphs/page_rank.py b/graphs/page_rank.py index b9e4c4a7..c0ce3a94 100644 --- a/graphs/page_rank.py +++ b/graphs/page_rank.py @@ -1,6 +1,7 @@ """ Author: https://github.com/bhushan-borole """ + """ The input graph for the algorithm is: diff --git a/graphs/prim.py b/graphs/prim.py index 6cb1a6de..5b3ce044 100644 --- a/graphs/prim.py +++ b/graphs/prim.py @@ -1,8 +1,8 @@ """Prim's Algorithm. - Determines the minimum spanning tree(MST) of a graph using the Prim's Algorithm. +Determines the minimum spanning tree(MST) of a graph using the Prim's Algorithm. - Details: https://en.wikipedia.org/wiki/Prim%27s_algorithm +Details: https://en.wikipedia.org/wiki/Prim%27s_algorithm """ import heapq as hq diff --git a/greedy_methods/gas_station.py b/greedy_methods/gas_station.py index 2427375d..6391ce37 100644 --- a/greedy_methods/gas_station.py +++ b/greedy_methods/gas_station.py @@ -23,6 +23,7 @@ If the net gain ever goes below 0 while iterating through the stations, start checking from the next station. """ + from dataclasses import dataclass diff --git a/hashes/adler32.py b/hashes/adler32.py index 611ebc88..38d76ab1 100644 --- a/hashes/adler32.py +++ b/hashes/adler32.py @@ -1,11 +1,11 @@ """ - Adler-32 is a checksum algorithm which was invented by Mark Adler in 1995. - Compared to a cyclic redundancy check of the same length, it trades reliability for - speed (preferring the latter). - Adler-32 is more reliable than Fletcher-16, and slightly less reliable than - Fletcher-32.[2] +Adler-32 is a checksum algorithm which was invented by Mark Adler in 1995. +Compared to a cyclic redundancy check of the same length, it trades reliability for +speed (preferring the latter). +Adler-32 is more reliable than Fletcher-16, and slightly less reliable than +Fletcher-32.[2] - source: https://en.wikipedia.org/wiki/Adler-32 +source: https://en.wikipedia.org/wiki/Adler-32 """ MOD_ADLER = 65521 diff --git a/hashes/hamming_code.py b/hashes/hamming_code.py index b34fdd4c..b3095852 100644 --- a/hashes/hamming_code.py +++ b/hashes/hamming_code.py @@ -4,44 +4,44 @@ # Black: True """ - * This code implement the Hamming code: - https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, - Hamming codes are a family of linear error-correcting codes. Hamming - codes can detect up to two-bit errors or correct one-bit errors - without detection of uncorrected errors. By contrast, the simple - parity code cannot correct errors, and can detect only an odd number - of bits in error. Hamming codes are perfect codes, that is, they - achieve the highest possible rate for codes with their block length - and minimum distance of three. +* This code implement the Hamming code: + https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, +Hamming codes are a family of linear error-correcting codes. Hamming +codes can detect up to two-bit errors or correct one-bit errors +without detection of uncorrected errors. By contrast, the simple +parity code cannot correct errors, and can detect only an odd number +of bits in error. Hamming codes are perfect codes, that is, they +achieve the highest possible rate for codes with their block length +and minimum distance of three. - * the implemented code consists of: - * a function responsible for encoding the message (emitterConverter) - * return the encoded message - * a function responsible for decoding the message (receptorConverter) - * return the decoded message and a ack of data integrity +* the implemented code consists of: + * a function responsible for encoding the message (emitterConverter) + * return the encoded message + * a function responsible for decoding the message (receptorConverter) + * return the decoded message and a ack of data integrity - * how to use: - to be used you must declare how many parity bits (sizePari) - you want to include in the message. - it is desired (for test purposes) to select a bit to be set - as an error. This serves to check whether the code is working correctly. - Lastly, the variable of the message/word that must be desired to be - encoded (text). +* how to use: + to be used you must declare how many parity bits (sizePari) + you want to include in the message. + it is desired (for test purposes) to select a bit to be set + as an error. This serves to check whether the code is working correctly. + Lastly, the variable of the message/word that must be desired to be + encoded (text). - * how this work: - declaration of variables (sizePari, be, text) +* how this work: + declaration of variables (sizePari, be, text) - converts the message/word (text) to binary using the - text_to_bits function - encodes the message using the rules of hamming encoding - decodes the message using the rules of hamming encoding - print the original message, the encoded message and the - decoded message + converts the message/word (text) to binary using the + text_to_bits function + encodes the message using the rules of hamming encoding + decodes the message using the rules of hamming encoding + print the original message, the encoded message and the + decoded message - forces an error in the coded text variable - decodes the message that was forced the error - print the original message, the encoded message, the bit changed - message and the decoded message + forces an error in the coded text variable + decodes the message that was forced the error + print the original message, the encoded message, the bit changed + message and the decoded message """ # Imports diff --git a/hashes/luhn.py b/hashes/luhn.py index bb77fd05..a29bf39e 100644 --- a/hashes/luhn.py +++ b/hashes/luhn.py @@ -1,4 +1,5 @@ -""" Luhn Algorithm """ +"""Luhn Algorithm""" + from __future__ import annotations diff --git a/hashes/sdbm.py b/hashes/sdbm.py index a5432874..a5abc6f3 100644 --- a/hashes/sdbm.py +++ b/hashes/sdbm.py @@ -1,21 +1,21 @@ """ - This algorithm was created for sdbm (a public-domain reimplementation of ndbm) - database library. - It was found to do well in scrambling bits, causing better distribution of the keys - and fewer splits. - It also happens to be a good general hashing function with good distribution. - The actual function (pseudo code) is: - for i in i..len(str): - hash(i) = hash(i - 1) * 65599 + str[i]; +This algorithm was created for sdbm (a public-domain reimplementation of ndbm) +database library. +It was found to do well in scrambling bits, causing better distribution of the keys +and fewer splits. +It also happens to be a good general hashing function with good distribution. +The actual function (pseudo code) is: + for i in i..len(str): + hash(i) = hash(i - 1) * 65599 + str[i]; - What is included below is the faster version used in gawk. [there is even a faster, - duff-device version] - The magic constant 65599 was picked out of thin air while experimenting with - different constants. - It turns out to be a prime. - This is one of the algorithms used in berkeley db (see sleepycat) and elsewhere. +What is included below is the faster version used in gawk. [there is even a faster, +duff-device version] +The magic constant 65599 was picked out of thin air while experimenting with +different constants. +It turns out to be a prime. +This is one of the algorithms used in berkeley db (see sleepycat) and elsewhere. - source: http://www.cse.yorku.ca/~oz/hash.html +source: http://www.cse.yorku.ca/~oz/hash.html """ diff --git a/hashes/sha1.py b/hashes/sha1.py index a0fa688f..75a1423e 100644 --- a/hashes/sha1.py +++ b/hashes/sha1.py @@ -25,6 +25,7 @@ the final hash. Reference: https://deadhacker.com/2006/02/21/sha-1-illustrated/ """ + import argparse import hashlib # hashlib is only used inside the Test class import struct diff --git a/knapsack/knapsack.py b/knapsack/knapsack.py index 18a36c3b..bb507be1 100644 --- a/knapsack/knapsack.py +++ b/knapsack/knapsack.py @@ -1,6 +1,7 @@ -""" A naive recursive implementation of 0-1 Knapsack Problem - https://en.wikipedia.org/wiki/Knapsack_problem +"""A naive recursive implementation of 0-1 Knapsack Problem +https://en.wikipedia.org/wiki/Knapsack_problem """ + from __future__ import annotations diff --git a/knapsack/tests/test_knapsack.py b/knapsack/tests/test_knapsack.py index 6932bbb3..7bfb8780 100644 --- a/knapsack/tests/test_knapsack.py +++ b/knapsack/tests/test_knapsack.py @@ -6,6 +6,7 @@ Created on Fri Oct 16 09:31:07 2020 This file contains the test-suite for the knapsack problem. """ + import unittest from knapsack import knapsack as k diff --git a/linear_algebra/gaussian_elimination.py b/linear_algebra/gaussian_elimination.py index a1a35131..724773c0 100644 --- a/linear_algebra/gaussian_elimination.py +++ b/linear_algebra/gaussian_elimination.py @@ -3,7 +3,6 @@ Gaussian elimination method for solving a system of linear equations. Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination """ - import numpy as np from numpy import float64 from numpy.typing import NDArray diff --git a/linear_algebra/jacobi_iteration_method.py b/linear_algebra/jacobi_iteration_method.py index 8c91a19e..2cc9c103 100644 --- a/linear_algebra/jacobi_iteration_method.py +++ b/linear_algebra/jacobi_iteration_method.py @@ -1,6 +1,7 @@ """ Jacobi Iteration Method - https://en.wikipedia.org/wiki/Jacobi_method """ + from __future__ import annotations import numpy as np diff --git a/linear_algebra/lu_decomposition.py b/linear_algebra/lu_decomposition.py index 094b20ab..1d364163 100644 --- a/linear_algebra/lu_decomposition.py +++ b/linear_algebra/lu_decomposition.py @@ -15,6 +15,7 @@ matrix and raise an error if no such decomposition exists. Reference: https://en.wikipedia.org/wiki/LU_decomposition """ + from __future__ import annotations import numpy as np diff --git a/linear_algebra/src/conjugate_gradient.py b/linear_algebra/src/conjugate_gradient.py index 4cf566ec..4c0b58de 100644 --- a/linear_algebra/src/conjugate_gradient.py +++ b/linear_algebra/src/conjugate_gradient.py @@ -3,6 +3,7 @@ Resources: - https://en.wikipedia.org/wiki/Conjugate_gradient_method - https://en.wikipedia.org/wiki/Definite_symmetric_matrix """ + from typing import Any import numpy as np diff --git a/linear_algebra/src/lib.py b/linear_algebra/src/lib.py index 5074faf3..5af6c62e 100644 --- a/linear_algebra/src/lib.py +++ b/linear_algebra/src/lib.py @@ -18,6 +18,7 @@ Overview: - function square_zero_matrix(N) - function random_matrix(W, H, a, b) """ + from __future__ import annotations import math @@ -96,12 +97,10 @@ class Vector: raise Exception("must have the same size") @overload - def __mul__(self, other: float) -> Vector: - ... + def __mul__(self, other: float) -> Vector: ... @overload - def __mul__(self, other: Vector) -> float: - ... + def __mul__(self, other: Vector) -> float: ... def __mul__(self, other: float | Vector) -> float | Vector: """ @@ -309,12 +308,10 @@ class Matrix: raise Exception("matrices must have the same dimension!") @overload - def __mul__(self, other: float) -> Matrix: - ... + def __mul__(self, other: float) -> Matrix: ... @overload - def __mul__(self, other: Vector) -> Vector: - ... + def __mul__(self, other: Vector) -> Vector: ... def __mul__(self, other: float | Vector) -> Vector | Matrix: """ diff --git a/linear_algebra/src/rayleigh_quotient.py b/linear_algebra/src/rayleigh_quotient.py index 4773429c..46bf1671 100644 --- a/linear_algebra/src/rayleigh_quotient.py +++ b/linear_algebra/src/rayleigh_quotient.py @@ -1,6 +1,7 @@ """ https://en.wikipedia.org/wiki/Rayleigh_quotient """ + from typing import Any import numpy as np diff --git a/linear_algebra/src/test_linear_algebra.py b/linear_algebra/src/test_linear_algebra.py index 95ab408b..fc5f90fd 100644 --- a/linear_algebra/src/test_linear_algebra.py +++ b/linear_algebra/src/test_linear_algebra.py @@ -6,6 +6,7 @@ Created on Mon Feb 26 15:40:07 2018 This file contains the test-suite for the linear algebra library. """ + import unittest import pytest diff --git a/linear_algebra/src/transformations_2d.py b/linear_algebra/src/transformations_2d.py index cdf42100..b4185cd2 100644 --- a/linear_algebra/src/transformations_2d.py +++ b/linear_algebra/src/transformations_2d.py @@ -11,6 +11,7 @@ projection(45) = [[0.27596319193541496, 0.446998331800279], reflection(45) = [[0.05064397763545947, 0.893996663600558], [0.893996663600558, 0.7018070490682369]] """ + from math import cos, sin diff --git a/linear_programming/simplex.py b/linear_programming/simplex.py index bbc97d8e..dc171bac 100644 --- a/linear_programming/simplex.py +++ b/linear_programming/simplex.py @@ -12,6 +12,7 @@ Resources: https://en.wikipedia.org/wiki/Simplex_algorithm https://tinyurl.com/simplex4beginners """ + from typing import Any import numpy as np diff --git a/machine_learning/apriori_algorithm.py b/machine_learning/apriori_algorithm.py index d9fd1f82..09a89ac2 100644 --- a/machine_learning/apriori_algorithm.py +++ b/machine_learning/apriori_algorithm.py @@ -10,6 +10,7 @@ indicating that customers who purchased A and B are more likely to also purchase WIKI: https://en.wikipedia.org/wiki/Apriori_algorithm Examples: https://www.kaggle.com/code/earthian/apriori-association-rules-mining """ + from itertools import combinations diff --git a/machine_learning/astar.py b/machine_learning/astar.py index ff520826..a5859e51 100644 --- a/machine_learning/astar.py +++ b/machine_learning/astar.py @@ -12,6 +12,7 @@ reason, A* is known as an algorithm with brains. https://en.wikipedia.org/wiki/A*_search_algorithm """ + import numpy as np diff --git a/machine_learning/automatic_differentiation.py b/machine_learning/automatic_differentiation.py index cd2e5cda..5c270824 100644 --- a/machine_learning/automatic_differentiation.py +++ b/machine_learning/automatic_differentiation.py @@ -6,6 +6,7 @@ Reference: https://en.wikipedia.org/wiki/Automatic_differentiation Author: Poojan Smart Email: smrtpoojan@gmail.com """ + from __future__ import annotations from collections import defaultdict diff --git a/machine_learning/data_transformations.py b/machine_learning/data_transformations.py index ecfd3b9e..a1c28d51 100644 --- a/machine_learning/data_transformations.py +++ b/machine_learning/data_transformations.py @@ -25,6 +25,7 @@ Additionally, a few rules of thumb are: 2. non-gaussian (non-normal) distributions work better with normalization 3. If a column or list of values has extreme values / outliers, use standardization """ + from statistics import mean, stdev diff --git a/machine_learning/decision_tree.py b/machine_learning/decision_tree.py index c67e09c7..7f129919 100644 --- a/machine_learning/decision_tree.py +++ b/machine_learning/decision_tree.py @@ -3,6 +3,7 @@ Implementation of a basic regression decision tree. Input data set: The input data set must be 1-dimensional with continuous labels. Output: The decision tree maps a real number input to a real number output. """ + import numpy as np diff --git a/machine_learning/frequent_pattern_growth.py b/machine_learning/frequent_pattern_growth.py index 205d5984..6b9870f5 100644 --- a/machine_learning/frequent_pattern_growth.py +++ b/machine_learning/frequent_pattern_growth.py @@ -9,6 +9,7 @@ WIKI: https://athena.ecs.csus.edu/~mei/associationcw/FpGrowth.html Examples: https://www.javatpoint.com/fp-growth-algorithm-in-data-mining """ + from __future__ import annotations from dataclasses import dataclass, field diff --git a/machine_learning/gradient_descent.py b/machine_learning/gradient_descent.py index 9ffc02bb..db38b3c9 100644 --- a/machine_learning/gradient_descent.py +++ b/machine_learning/gradient_descent.py @@ -2,6 +2,7 @@ Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function. """ + import numpy # List of input, output pairs diff --git a/machine_learning/k_means_clust.py b/machine_learning/k_means_clust.py index 4a219edc..9f664694 100644 --- a/machine_learning/k_means_clust.py +++ b/machine_learning/k_means_clust.py @@ -40,6 +40,7 @@ Usage: 5. Transfers Dataframe into excel format it must have feature called 'Clust' with k means clustering numbers in it. """ + import warnings import numpy as np diff --git a/machine_learning/linear_discriminant_analysis.py b/machine_learning/linear_discriminant_analysis.py index 88c04715..606e11f3 100644 --- a/machine_learning/linear_discriminant_analysis.py +++ b/machine_learning/linear_discriminant_analysis.py @@ -1,47 +1,48 @@ """ - Linear Discriminant Analysis +Linear Discriminant Analysis - Assumptions About Data : - 1. The input variables has a gaussian distribution. - 2. The variance calculated for each input variables by class grouping is the - same. - 3. The mix of classes in your training set is representative of the problem. +Assumptions About Data : + 1. The input variables has a gaussian distribution. + 2. The variance calculated for each input variables by class grouping is the + same. + 3. The mix of classes in your training set is representative of the problem. - Learning The Model : - The LDA model requires the estimation of statistics from the training data : - 1. Mean of each input value for each class. - 2. Probability of an instance belong to each class. - 3. Covariance for the input data for each class +Learning The Model : + The LDA model requires the estimation of statistics from the training data : + 1. Mean of each input value for each class. + 2. Probability of an instance belong to each class. + 3. Covariance for the input data for each class - Calculate the class means : - mean(x) = 1/n ( for i = 1 to i = n --> sum(xi)) + Calculate the class means : + mean(x) = 1/n ( for i = 1 to i = n --> sum(xi)) - Calculate the class probabilities : - P(y = 0) = count(y = 0) / (count(y = 0) + count(y = 1)) - P(y = 1) = count(y = 1) / (count(y = 0) + count(y = 1)) + Calculate the class probabilities : + P(y = 0) = count(y = 0) / (count(y = 0) + count(y = 1)) + P(y = 1) = count(y = 1) / (count(y = 0) + count(y = 1)) - Calculate the variance : - We can calculate the variance for dataset in two steps : - 1. Calculate the squared difference for each input variable from the - group mean. - 2. Calculate the mean of the squared difference. - ------------------------------------------------ - Squared_Difference = (x - mean(k)) ** 2 - Variance = (1 / (count(x) - count(classes))) * - (for i = 1 to i = n --> sum(Squared_Difference(xi))) + Calculate the variance : + We can calculate the variance for dataset in two steps : + 1. Calculate the squared difference for each input variable from the + group mean. + 2. Calculate the mean of the squared difference. + ------------------------------------------------ + Squared_Difference = (x - mean(k)) ** 2 + Variance = (1 / (count(x) - count(classes))) * + (for i = 1 to i = n --> sum(Squared_Difference(xi))) - Making Predictions : - discriminant(x) = x * (mean / variance) - - ((mean ** 2) / (2 * variance)) + Ln(probability) - --------------------------------------------------------------------------- - After calculating the discriminant value for each class, the class with the - largest discriminant value is taken as the prediction. +Making Predictions : + discriminant(x) = x * (mean / variance) - + ((mean ** 2) / (2 * variance)) + Ln(probability) + --------------------------------------------------------------------------- + After calculating the discriminant value for each class, the class with the + largest discriminant value is taken as the prediction. - Author: @EverLookNeverSee +Author: @EverLookNeverSee """ + from collections.abc import Callable from math import log from os import name, system diff --git a/machine_learning/linear_regression.py b/machine_learning/linear_regression.py index 0847112a..39bee571 100644 --- a/machine_learning/linear_regression.py +++ b/machine_learning/linear_regression.py @@ -7,6 +7,7 @@ We try to set the weight of these features, over many iterations, so that they b fit our dataset. In this particular code, I had used a CSGO dataset (ADR vs Rating). We try to best fit a line through dataset and estimate the parameters. """ + import numpy as np import requests diff --git a/machine_learning/logistic_regression.py b/machine_learning/logistic_regression.py index 59a70fd6..090af538 100644 --- a/machine_learning/logistic_regression.py +++ b/machine_learning/logistic_regression.py @@ -14,6 +14,7 @@ Helpful resources: Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ + import numpy as np from matplotlib import pyplot as plt from sklearn import datasets diff --git a/machine_learning/lstm/lstm_prediction.py b/machine_learning/lstm/lstm_prediction.py index ecbd4512..f0fd12c9 100644 --- a/machine_learning/lstm/lstm_prediction.py +++ b/machine_learning/lstm/lstm_prediction.py @@ -1,9 +1,10 @@ """ - Create a Long Short Term Memory (LSTM) network model - An LSTM is a type of Recurrent Neural Network (RNN) as discussed at: - * https://colah.github.io/posts/2015-08-Understanding-LSTMs - * https://en.wikipedia.org/wiki/Long_short-term_memory +Create a Long Short Term Memory (LSTM) network model +An LSTM is a type of Recurrent Neural Network (RNN) as discussed at: +* https://colah.github.io/posts/2015-08-Understanding-LSTMs +* https://en.wikipedia.org/wiki/Long_short-term_memory """ + import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler diff --git a/machine_learning/mfcc.py b/machine_learning/mfcc.py index 7ce8ceb5..a1e99ce4 100644 --- a/machine_learning/mfcc.py +++ b/machine_learning/mfcc.py @@ -57,7 +57,6 @@ References: Author: Amir Lavasani """ - import logging import numpy as np diff --git a/machine_learning/self_organizing_map.py b/machine_learning/self_organizing_map.py index 32fdf1d2..fb9d0074 100644 --- a/machine_learning/self_organizing_map.py +++ b/machine_learning/self_organizing_map.py @@ -1,6 +1,7 @@ """ https://en.wikipedia.org/wiki/Self-organizing_map """ + import math diff --git a/machine_learning/sequential_minimum_optimization.py b/machine_learning/sequential_minimum_optimization.py index 9ee8c52f..be16baca 100644 --- a/machine_learning/sequential_minimum_optimization.py +++ b/machine_learning/sequential_minimum_optimization.py @@ -30,7 +30,6 @@ Reference: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-98-14.pdf """ - import os import sys import urllib.request diff --git a/machine_learning/similarity_search.py b/machine_learning/similarity_search.py index 7a23ec46..0bc3b17d 100644 --- a/machine_learning/similarity_search.py +++ b/machine_learning/similarity_search.py @@ -7,6 +7,7 @@ returns a list containing two data for each vector: 1. the nearest vector 2. distance between the vector and the nearest vector (float) """ + from __future__ import annotations import math diff --git a/maths/allocation_number.py b/maths/allocation_number.py index d419e74d..52f1ac4b 100644 --- a/maths/allocation_number.py +++ b/maths/allocation_number.py @@ -5,6 +5,7 @@ For example: for i in allocation_list: requests.get(url,headers={'Range':f'bytes={i}'}) """ + from __future__ import annotations diff --git a/maths/area.py b/maths/area.py index ea7216c8..31a65420 100644 --- a/maths/area.py +++ b/maths/area.py @@ -2,6 +2,7 @@ Find the area of various geometric shapes Wikipedia reference: https://en.wikipedia.org/wiki/Area """ + from math import pi, sqrt, tan diff --git a/maths/area_under_curve.py b/maths/area_under_curve.py index 0da6546b..10aec768 100644 --- a/maths/area_under_curve.py +++ b/maths/area_under_curve.py @@ -1,6 +1,7 @@ """ Approximates the area under the curve using the trapezoidal rule """ + from __future__ import annotations from collections.abc import Callable diff --git a/maths/basic_maths.py b/maths/basic_maths.py index c9e3d00f..833f31c1 100644 --- a/maths/basic_maths.py +++ b/maths/basic_maths.py @@ -1,4 +1,5 @@ """Implementation of Basic Math in Python.""" + import math diff --git a/maths/binomial_distribution.py b/maths/binomial_distribution.py index 5b56f2d5..eabcaea0 100644 --- a/maths/binomial_distribution.py +++ b/maths/binomial_distribution.py @@ -1,5 +1,6 @@ """For more information about the Binomial Distribution - - https://en.wikipedia.org/wiki/Binomial_distribution""" +https://en.wikipedia.org/wiki/Binomial_distribution""" + from math import factorial diff --git a/maths/chinese_remainder_theorem.py b/maths/chinese_remainder_theorem.py index d3e75e77..18af63d1 100644 --- a/maths/chinese_remainder_theorem.py +++ b/maths/chinese_remainder_theorem.py @@ -11,6 +11,7 @@ Algorithm : 1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1 2. Take n = ra*by + rb*ax """ + from __future__ import annotations diff --git a/maths/continued_fraction.py b/maths/continued_fraction.py index 04ff0b6f..2c38bf88 100644 --- a/maths/continued_fraction.py +++ b/maths/continued_fraction.py @@ -4,7 +4,6 @@ Finding the continuous fraction for a rational number using python https://en.wikipedia.org/wiki/Continued_fraction """ - from fractions import Fraction from math import floor diff --git a/maths/entropy.py b/maths/entropy.py index 23753d88..76fac4ee 100644 --- a/maths/entropy.py +++ b/maths/entropy.py @@ -4,6 +4,7 @@ Implementation of entropy of information https://en.wikipedia.org/wiki/Entropy_(information_theory) """ + from __future__ import annotations import math diff --git a/maths/gamma.py b/maths/gamma.py index 822bbc74..e328cd8b 100644 --- a/maths/gamma.py +++ b/maths/gamma.py @@ -8,6 +8,7 @@ The gamma function is defined for all complex numbers except the non-positive integers Python's Standard Library math.gamma() function overflows around gamma(171.624). """ + import math from numpy import inf diff --git a/maths/gaussian.py b/maths/gaussian.py index 51ebc2e2..0e02010a 100644 --- a/maths/gaussian.py +++ b/maths/gaussian.py @@ -1,6 +1,7 @@ """ Reference: https://en.wikipedia.org/wiki/Gaussian_function """ + from numpy import exp, pi, sqrt diff --git a/maths/interquartile_range.py b/maths/interquartile_range.py index d4d72e73..e91a6516 100644 --- a/maths/interquartile_range.py +++ b/maths/interquartile_range.py @@ -7,6 +7,7 @@ The function takes the list of numeric values as input and returns the IQR. Script inspired by this Wikipedia article: https://en.wikipedia.org/wiki/Interquartile_range """ + from __future__ import annotations diff --git a/maths/is_square_free.py b/maths/is_square_free.py index 08c70dc3..a336c37e 100644 --- a/maths/is_square_free.py +++ b/maths/is_square_free.py @@ -3,6 +3,7 @@ References: wikipedia:square free number psf/black : True ruff : True """ + from __future__ import annotations diff --git a/maths/karatsuba.py b/maths/karatsuba.py index 3d29e31d..0e063fb4 100644 --- a/maths/karatsuba.py +++ b/maths/karatsuba.py @@ -1,4 +1,4 @@ -""" Multiply two numbers using Karatsuba algorithm """ +"""Multiply two numbers using Karatsuba algorithm""" def karatsuba(a: int, b: int) -> int: diff --git a/maths/lucas_lehmer_primality_test.py b/maths/lucas_lehmer_primality_test.py index 0a5621aa..29238741 100644 --- a/maths/lucas_lehmer_primality_test.py +++ b/maths/lucas_lehmer_primality_test.py @@ -1,13 +1,13 @@ """ - In mathematics, the Lucas–Lehmer test (LLT) is a primality test for Mersenne - numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test +In mathematics, the Lucas–Lehmer test (LLT) is a primality test for Mersenne +numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test - A Mersenne number is a number that is one less than a power of two. - That is M_p = 2^p - 1 - https://en.wikipedia.org/wiki/Mersenne_prime +A Mersenne number is a number that is one less than a power of two. +That is M_p = 2^p - 1 +https://en.wikipedia.org/wiki/Mersenne_prime - The Lucas–Lehmer test is the primality test used by the - Great Internet Mersenne Prime Search (GIMPS) to locate large primes. +The Lucas–Lehmer test is the primality test used by the +Great Internet Mersenne Prime Search (GIMPS) to locate large primes. """ diff --git a/maths/maclaurin_series.py b/maths/maclaurin_series.py index d5c3c3ab..6ec5551a 100644 --- a/maths/maclaurin_series.py +++ b/maths/maclaurin_series.py @@ -1,6 +1,7 @@ """ https://en.wikipedia.org/wiki/Taylor_series#Trigonometric_functions """ + from math import factorial, pi diff --git a/maths/max_sum_sliding_window.py b/maths/max_sum_sliding_window.py index c6f9b4ed..09011742 100644 --- a/maths/max_sum_sliding_window.py +++ b/maths/max_sum_sliding_window.py @@ -6,6 +6,7 @@ Instead of using a nested for loop, in a Brute force approach we will use a tech called 'Window sliding technique' where the nested loops can be converted to a single loop to reduce time complexity. """ + from __future__ import annotations diff --git a/maths/modular_exponential.py b/maths/modular_exponential.py index 42987dbf..a27e29eb 100644 --- a/maths/modular_exponential.py +++ b/maths/modular_exponential.py @@ -1,8 +1,8 @@ """ - Modular Exponential. - Modular exponentiation is a type of exponentiation performed over a modulus. - For more explanation, please check - https://en.wikipedia.org/wiki/Modular_exponentiation +Modular Exponential. +Modular exponentiation is a type of exponentiation performed over a modulus. +For more explanation, please check +https://en.wikipedia.org/wiki/Modular_exponentiation """ """Calculate Modular Exponential.""" diff --git a/maths/monte_carlo.py b/maths/monte_carlo.py index 474f1f65..d174a0b1 100644 --- a/maths/monte_carlo.py +++ b/maths/monte_carlo.py @@ -1,6 +1,7 @@ """ @author: MatteoRaso """ + from collections.abc import Callable from math import pi, sqrt from random import uniform diff --git a/maths/numerical_analysis/adams_bashforth.py b/maths/numerical_analysis/adams_bashforth.py index d61f022a..fb406171 100644 --- a/maths/numerical_analysis/adams_bashforth.py +++ b/maths/numerical_analysis/adams_bashforth.py @@ -4,6 +4,7 @@ Use the Adams-Bashforth methods to solve Ordinary Differential Equations. https://en.wikipedia.org/wiki/Linear_multistep_method Author : Ravi Kumar """ + from collections.abc import Callable from dataclasses import dataclass diff --git a/maths/numerical_analysis/nevilles_method.py b/maths/numerical_analysis/nevilles_method.py index 1f48b43f..256b61f5 100644 --- a/maths/numerical_analysis/nevilles_method.py +++ b/maths/numerical_analysis/nevilles_method.py @@ -1,11 +1,11 @@ """ - Python program to show how to interpolate and evaluate a polynomial - using Neville's method. - Neville’s method evaluates a polynomial that passes through a - given set of x and y points for a particular x value (x0) using the - Newton polynomial form. - Reference: - https://rpubs.com/aaronsc32/nevilles-method-polynomial-interpolation +Python program to show how to interpolate and evaluate a polynomial +using Neville's method. +Neville’s method evaluates a polynomial that passes through a +given set of x and y points for a particular x value (x0) using the +Newton polynomial form. +Reference: + https://rpubs.com/aaronsc32/nevilles-method-polynomial-interpolation """ diff --git a/maths/numerical_analysis/newton_raphson.py b/maths/numerical_analysis/newton_raphson.py index feee38f9..10fb244b 100644 --- a/maths/numerical_analysis/newton_raphson.py +++ b/maths/numerical_analysis/newton_raphson.py @@ -9,6 +9,7 @@ with the precision of the approximation increasing as the number of iterations i Reference: https://en.wikipedia.org/wiki/Newton%27s_method """ + from collections.abc import Callable RealFunc = Callable[[float], float] diff --git a/maths/numerical_analysis/numerical_integration.py b/maths/numerical_analysis/numerical_integration.py index 4ac56264..f64436ec 100644 --- a/maths/numerical_analysis/numerical_integration.py +++ b/maths/numerical_analysis/numerical_integration.py @@ -1,6 +1,7 @@ """ Approximates the area under the curve using the trapezoidal rule """ + from __future__ import annotations from collections.abc import Callable diff --git a/maths/numerical_analysis/runge_kutta_gills.py b/maths/numerical_analysis/runge_kutta_gills.py index 2bd9cd61..451cde4c 100644 --- a/maths/numerical_analysis/runge_kutta_gills.py +++ b/maths/numerical_analysis/runge_kutta_gills.py @@ -4,6 +4,7 @@ Use the Runge-Kutta-Gill's method of order 4 to solve Ordinary Differential Equa https://www.geeksforgeeks.org/gills-4th-order-method-to-solve-differential-equations/ Author : Ravi Kumar """ + from collections.abc import Callable from math import sqrt diff --git a/maths/numerical_analysis/secant_method.py b/maths/numerical_analysis/secant_method.py index d39cb0ff..9fff8222 100644 --- a/maths/numerical_analysis/secant_method.py +++ b/maths/numerical_analysis/secant_method.py @@ -2,6 +2,7 @@ Implementing Secant method in Python Author: dimgrichr """ + from math import exp diff --git a/maths/prime_factors.py b/maths/prime_factors.py index e520ae3a..47abcf10 100644 --- a/maths/prime_factors.py +++ b/maths/prime_factors.py @@ -1,6 +1,7 @@ """ python/black : True """ + from __future__ import annotations diff --git a/maths/series/geometric_series.py b/maths/series/geometric_series.py index b8d6a862..55c42fd9 100644 --- a/maths/series/geometric_series.py +++ b/maths/series/geometric_series.py @@ -9,7 +9,6 @@ For manual testing run: python3 geometric_series.py """ - from __future__ import annotations diff --git a/maths/series/p_series.py b/maths/series/p_series.py index a091a6f3..93812f44 100644 --- a/maths/series/p_series.py +++ b/maths/series/p_series.py @@ -9,7 +9,6 @@ For manual testing run: python3 p_series.py """ - from __future__ import annotations diff --git a/maths/sieve_of_eratosthenes.py b/maths/sieve_of_eratosthenes.py index a0520aa5..3923dc3e 100644 --- a/maths/sieve_of_eratosthenes.py +++ b/maths/sieve_of_eratosthenes.py @@ -10,6 +10,7 @@ Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich) Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem """ + from __future__ import annotations import math diff --git a/maths/solovay_strassen_primality_test.py b/maths/solovay_strassen_primality_test.py index 1d11d458..b2d905b0 100644 --- a/maths/solovay_strassen_primality_test.py +++ b/maths/solovay_strassen_primality_test.py @@ -9,7 +9,6 @@ More details and concepts about this can be found on: https://en.wikipedia.org/wiki/Solovay%E2%80%93Strassen_primality_test """ - import random diff --git a/maths/special_numbers/armstrong_numbers.py b/maths/special_numbers/armstrong_numbers.py index b037aacb..b2b4010a 100644 --- a/maths/special_numbers/armstrong_numbers.py +++ b/maths/special_numbers/armstrong_numbers.py @@ -8,6 +8,7 @@ Armstrong numbers are also called Narcissistic numbers and Pluperfect numbers. On-Line Encyclopedia of Integer Sequences entry: https://oeis.org/A005188 """ + PASSING = (1, 153, 370, 371, 1634, 24678051, 115132219018763992565095597973971522401) FAILING: tuple = (-153, -1, 0, 1.2, 200, "A", [], {}, None) diff --git a/maths/special_numbers/weird_number.py b/maths/special_numbers/weird_number.py index 2834a9fe..5c9240d0 100644 --- a/maths/special_numbers/weird_number.py +++ b/maths/special_numbers/weird_number.py @@ -3,6 +3,7 @@ https://en.wikipedia.org/wiki/Weird_number Fun fact: The set of weird numbers has positive asymptotic density. """ + from math import sqrt diff --git a/maths/tanh.py b/maths/tanh.py index 38a369d9..011d6f17 100644 --- a/maths/tanh.py +++ b/maths/tanh.py @@ -9,6 +9,7 @@ element of the vector mostly -1 between 1. Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Activation_function """ + import numpy as np diff --git a/maths/triplet_sum.py b/maths/triplet_sum.py index af77ed14..e74f67da 100644 --- a/maths/triplet_sum.py +++ b/maths/triplet_sum.py @@ -3,6 +3,7 @@ Given an array of integers and another integer target, we are required to find a triplet from the array such that it's sum is equal to the target. """ + from __future__ import annotations from itertools import permutations diff --git a/maths/two_pointer.py b/maths/two_pointer.py index d0fb0fc9..8a6d8eb7 100644 --- a/maths/two_pointer.py +++ b/maths/two_pointer.py @@ -17,6 +17,7 @@ return [0, 1]. [1]: https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py """ + from __future__ import annotations diff --git a/maths/two_sum.py b/maths/two_sum.py index 12ad332d..58c933a5 100644 --- a/maths/two_sum.py +++ b/maths/two_sum.py @@ -11,6 +11,7 @@ Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ + from __future__ import annotations diff --git a/maths/volume.py b/maths/volume.py index b4df4e47..33be9bdd 100644 --- a/maths/volume.py +++ b/maths/volume.py @@ -3,6 +3,7 @@ Find the volume of various shapes. * https://en.wikipedia.org/wiki/Volume * https://en.wikipedia.org/wiki/Spherical_cap """ + from __future__ import annotations from math import pi, pow diff --git a/matrix/matrix_multiplication_recursion.py b/matrix/matrix_multiplication_recursion.py index 28714248..57c4d80d 100644 --- a/matrix/matrix_multiplication_recursion.py +++ b/matrix/matrix_multiplication_recursion.py @@ -7,6 +7,7 @@ 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 Matrix = list[list[int]] diff --git a/networking_flow/ford_fulkerson.py b/networking_flow/ford_fulkerson.py index 7d5fb522..b47d3b68 100644 --- a/networking_flow/ford_fulkerson.py +++ b/networking_flow/ford_fulkerson.py @@ -6,6 +6,7 @@ Description: (1) Start with initial flow as 0 (2) Choose the augmenting path from source to sink and add the path to flow """ + graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], diff --git a/neural_network/activation_functions/binary_step.py b/neural_network/activation_functions/binary_step.py index 8f8f4d40..d3d77460 100644 --- a/neural_network/activation_functions/binary_step.py +++ b/neural_network/activation_functions/binary_step.py @@ -8,7 +8,6 @@ It's a simple activation function which is mentioned in this wikipedia article: https://en.wikipedia.org/wiki/Activation_function """ - import numpy as np diff --git a/neural_network/activation_functions/rectified_linear_unit.py b/neural_network/activation_functions/rectified_linear_unit.py index 458c6bd5..2d5cf96f 100644 --- a/neural_network/activation_functions/rectified_linear_unit.py +++ b/neural_network/activation_functions/rectified_linear_unit.py @@ -9,6 +9,7 @@ After through ReLU, the element of the vector always 0 or real number. Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Rectifier_(neural_networks) """ + from __future__ import annotations import numpy as np diff --git a/neural_network/activation_functions/soboleva_modified_hyperbolic_tangent.py b/neural_network/activation_functions/soboleva_modified_hyperbolic_tangent.py index 603ac0b7..a053e690 100644 --- a/neural_network/activation_functions/soboleva_modified_hyperbolic_tangent.py +++ b/neural_network/activation_functions/soboleva_modified_hyperbolic_tangent.py @@ -8,7 +8,6 @@ More details about the activation function can be found on: https://en.wikipedia.org/wiki/Soboleva_modified_hyperbolic_tangent """ - import numpy as np diff --git a/neural_network/back_propagation_neural_network.py b/neural_network/back_propagation_neural_network.py index bdd096b3..7e0bdbbe 100644 --- a/neural_network/back_propagation_neural_network.py +++ b/neural_network/back_propagation_neural_network.py @@ -17,6 +17,7 @@ Github : https://github.com/RiptideBo Date: 2017.11.23 """ + import numpy as np from matplotlib import pyplot as plt diff --git a/neural_network/convolution_neural_network.py b/neural_network/convolution_neural_network.py index e9726a0c..07cc456b 100644 --- a/neural_network/convolution_neural_network.py +++ b/neural_network/convolution_neural_network.py @@ -1,18 +1,19 @@ """ - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - - Name - - CNN - Convolution Neural Network For Photo Recognizing - Goal - - Recognize Handing Writing Word Photo - Detail: Total 5 layers neural network - * Convolution layer - * Pooling layer - * Input layer layer of BP - * Hidden layer of BP - * Output layer of BP - Author: Stephen Lee - Github: 245885195@qq.com - Date: 2017.9.20 - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - + - - - - - -- - - - - - - - - - - - - - - - - - - - - - - +Name - - CNN - Convolution Neural Network For Photo Recognizing +Goal - - Recognize Handing Writing Word Photo +Detail: Total 5 layers neural network + * Convolution layer + * Pooling layer + * Input layer layer of BP + * Hidden layer of BP + * Output layer of BP +Author: Stephen Lee +Github: 245885195@qq.com +Date: 2017.9.20 +- - - - - -- - - - - - - - - - - - - - - - - - - - - - - """ + import pickle import numpy as np diff --git a/neural_network/input_data.py b/neural_network/input_data.py index 2128449c..f7ae86b4 100644 --- a/neural_network/input_data.py +++ b/neural_network/input_data.py @@ -17,7 +17,6 @@ This module and all its submodules are deprecated. """ - import gzip import os import typing diff --git a/other/davis_putnam_logemann_loveland.py b/other/davis_putnam_logemann_loveland.py index f5fb103b..436577eb 100644 --- a/other/davis_putnam_logemann_loveland.py +++ b/other/davis_putnam_logemann_loveland.py @@ -8,6 +8,7 @@ conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiabi For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm """ + from __future__ import annotations import random diff --git a/other/fischer_yates_shuffle.py b/other/fischer_yates_shuffle.py index fa2f4dce..37e11479 100644 --- a/other/fischer_yates_shuffle.py +++ b/other/fischer_yates_shuffle.py @@ -5,6 +5,7 @@ finite sequence. For more details visit wikipedia/Fischer-Yates-Shuffle. """ + import random from typing import Any diff --git a/other/gauss_easter.py b/other/gauss_easter.py index 4447d4ab..d1c52559 100644 --- a/other/gauss_easter.py +++ b/other/gauss_easter.py @@ -1,6 +1,7 @@ """ https://en.wikipedia.org/wiki/Computus#Gauss'_Easter_algorithm """ + import math from datetime import datetime, timedelta diff --git a/other/majority_vote_algorithm.py b/other/majority_vote_algorithm.py index ab8b386d..8d3b5670 100644 --- a/other/majority_vote_algorithm.py +++ b/other/majority_vote_algorithm.py @@ -4,6 +4,7 @@ Given an integer array of size n, find all elements that appear more than ⌊ n/ We have to solve in O(n) time and O(1) Space. URL : https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm """ + from collections import Counter diff --git a/other/quine.py b/other/quine.py index 500a351d..08e885bc 100644 --- a/other/quine.py +++ b/other/quine.py @@ -8,4 +8,5 @@ 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))")) diff --git a/other/word_search.py b/other/word_search.py index a4796e22..9e8acadb 100644 --- a/other/word_search.py +++ b/other/word_search.py @@ -5,7 +5,6 @@ that are best described as compass locations. @ https://en.wikipedia.org/wiki/Word_search """ - from random import choice, randint, shuffle # The words to display on the word search - diff --git a/physics/archimedes_principle_of_buoyant_force.py b/physics/archimedes_principle_of_buoyant_force.py index 5f569837..71043e0e 100644 --- a/physics/archimedes_principle_of_buoyant_force.py +++ b/physics/archimedes_principle_of_buoyant_force.py @@ -8,7 +8,6 @@ Fb = ρ * V * g https://en.wikipedia.org/wiki/Archimedes%27_principle """ - # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 # Also available in scipy.constants.g diff --git a/physics/center_of_mass.py b/physics/center_of_mass.py index bd9ba248..59c3b807 100644 --- a/physics/center_of_mass.py +++ b/physics/center_of_mass.py @@ -24,6 +24,7 @@ R = (Σ(mi * ri) / Σ(mi)) Reference: https://en.wikipedia.org/wiki/Center_of_mass """ + from collections import namedtuple Particle = namedtuple("Particle", "x y z mass") # noqa: PYI024 diff --git a/physics/in_static_equilibrium.py b/physics/in_static_equilibrium.py index d56299f6..e3c2f9d0 100644 --- a/physics/in_static_equilibrium.py +++ b/physics/in_static_equilibrium.py @@ -1,6 +1,7 @@ """ Checks if a system of forces is in static equilibrium. """ + from __future__ import annotations from numpy import array, cos, cross, float64, radians, sin diff --git a/physics/n_body_simulation.py b/physics/n_body_simulation.py index ec008784..4d555716 100644 --- a/physics/n_body_simulation.py +++ b/physics/n_body_simulation.py @@ -11,7 +11,6 @@ goes to infinity). (See also http://www.shodor.org/refdesk/Resources/Algorithms/EulersMethod/ ) """ - from __future__ import annotations import random diff --git a/physics/rms_speed_of_molecule.py b/physics/rms_speed_of_molecule.py index 478cee01..fb23eb8a 100644 --- a/physics/rms_speed_of_molecule.py +++ b/physics/rms_speed_of_molecule.py @@ -20,7 +20,6 @@ zero; as this value is unhelpful, the average of velocities can be determined us alternative method. """ - UNIVERSAL_GAS_CONSTANT = 8.3144598 diff --git a/project_euler/problem_002/sol4.py b/project_euler/problem_002/sol4.py index 70b7d6a8..3a2e4fce 100644 --- a/project_euler/problem_002/sol4.py +++ b/project_euler/problem_002/sol4.py @@ -14,6 +14,7 @@ four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ + import math from decimal import Decimal, getcontext diff --git a/project_euler/problem_003/sol1.py b/project_euler/problem_003/sol1.py index a7d01bb0..d1c0e61c 100644 --- a/project_euler/problem_003/sol1.py +++ b/project_euler/problem_003/sol1.py @@ -10,6 +10,7 @@ What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ + import math diff --git a/project_euler/problem_006/sol3.py b/project_euler/problem_006/sol3.py index 529f233c..16445258 100644 --- a/project_euler/problem_006/sol3.py +++ b/project_euler/problem_006/sol3.py @@ -15,6 +15,7 @@ natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ + import math diff --git a/project_euler/problem_007/sol2.py b/project_euler/problem_007/sol2.py index 75d35188..fd99453c 100644 --- a/project_euler/problem_007/sol2.py +++ b/project_euler/problem_007/sol2.py @@ -11,6 +11,7 @@ What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ + import math diff --git a/project_euler/problem_007/sol3.py b/project_euler/problem_007/sol3.py index 774260db..39db51a9 100644 --- a/project_euler/problem_007/sol3.py +++ b/project_euler/problem_007/sol3.py @@ -11,6 +11,7 @@ What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ + import itertools import math diff --git a/project_euler/problem_008/sol2.py b/project_euler/problem_008/sol2.py index 889c3a31..f83cb1db 100644 --- a/project_euler/problem_008/sol2.py +++ b/project_euler/problem_008/sol2.py @@ -30,6 +30,7 @@ product are 9 × 9 × 8 × 9 = 5832. Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ + from functools import reduce N = ( diff --git a/project_euler/problem_008/sol3.py b/project_euler/problem_008/sol3.py index c6081aa0..bf3bcb05 100644 --- a/project_euler/problem_008/sol3.py +++ b/project_euler/problem_008/sol3.py @@ -30,6 +30,7 @@ product are 9 × 9 × 8 × 9 = 5832. Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ + import sys N = ( diff --git a/project_euler/problem_010/sol2.py b/project_euler/problem_010/sol2.py index 245cca1d..1a1fc0f3 100644 --- a/project_euler/problem_010/sol2.py +++ b/project_euler/problem_010/sol2.py @@ -10,6 +10,7 @@ Find the sum of all the primes below two million. References: - https://en.wikipedia.org/wiki/Prime_number """ + import math from collections.abc import Iterator from itertools import takewhile diff --git a/project_euler/problem_013/sol1.py b/project_euler/problem_013/sol1.py index 7a414a93..87d0e0a6 100644 --- a/project_euler/problem_013/sol1.py +++ b/project_euler/problem_013/sol1.py @@ -5,6 +5,7 @@ Problem Statement: Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. """ + import os diff --git a/project_euler/problem_014/sol2.py b/project_euler/problem_014/sol2.py index 2448e652..797b0f98 100644 --- a/project_euler/problem_014/sol2.py +++ b/project_euler/problem_014/sol2.py @@ -25,6 +25,7 @@ that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? """ + from __future__ import annotations COLLATZ_SEQUENCE_LENGTHS = {1: 1} diff --git a/project_euler/problem_015/sol1.py b/project_euler/problem_015/sol1.py index fb2020d6..fd9014a4 100644 --- a/project_euler/problem_015/sol1.py +++ b/project_euler/problem_015/sol1.py @@ -5,6 +5,7 @@ Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? """ + from math import factorial diff --git a/project_euler/problem_018/solution.py b/project_euler/problem_018/solution.py index 70306148..cbe8743b 100644 --- a/project_euler/problem_018/solution.py +++ b/project_euler/problem_018/solution.py @@ -27,6 +27,7 @@ Find the maximum total from top to bottom of the triangle below: 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 """ + import os diff --git a/project_euler/problem_020/sol2.py b/project_euler/problem_020/sol2.py index 676e96e7..a1d56ade 100644 --- a/project_euler/problem_020/sol2.py +++ b/project_euler/problem_020/sol2.py @@ -8,6 +8,7 @@ and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ + from math import factorial diff --git a/project_euler/problem_020/sol3.py b/project_euler/problem_020/sol3.py index 4f28ac5f..1886e054 100644 --- a/project_euler/problem_020/sol3.py +++ b/project_euler/problem_020/sol3.py @@ -8,6 +8,7 @@ and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ + from math import factorial diff --git a/project_euler/problem_021/sol1.py b/project_euler/problem_021/sol1.py index 353510ae..f6dbfa88 100644 --- a/project_euler/problem_021/sol1.py +++ b/project_euler/problem_021/sol1.py @@ -13,6 +13,7 @@ and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and Evaluate the sum of all the amicable numbers under 10000. """ + from math import sqrt diff --git a/project_euler/problem_022/sol1.py b/project_euler/problem_022/sol1.py index 98290624..b6386186 100644 --- a/project_euler/problem_022/sol1.py +++ b/project_euler/problem_022/sol1.py @@ -14,6 +14,7 @@ obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ + import os diff --git a/project_euler/problem_022/sol2.py b/project_euler/problem_022/sol2.py index 5ae41c84..f7092ea1 100644 --- a/project_euler/problem_022/sol2.py +++ b/project_euler/problem_022/sol2.py @@ -14,6 +14,7 @@ obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ + import os diff --git a/project_euler/problem_024/sol1.py b/project_euler/problem_024/sol1.py index 1c6378b3..3fb1bd4e 100644 --- a/project_euler/problem_024/sol1.py +++ b/project_euler/problem_024/sol1.py @@ -9,6 +9,7 @@ lexicographic permutations of 0, 1 and 2 are: What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ + from itertools import permutations diff --git a/project_euler/problem_025/sol2.py b/project_euler/problem_025/sol2.py index 6f49e89f..9e950b35 100644 --- a/project_euler/problem_025/sol2.py +++ b/project_euler/problem_025/sol2.py @@ -23,6 +23,7 @@ The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ + from collections.abc import Generator diff --git a/project_euler/problem_030/sol1.py b/project_euler/problem_030/sol1.py index 2c6b4e4e..7d83e314 100644 --- a/project_euler/problem_030/sol1.py +++ b/project_euler/problem_030/sol1.py @@ -1,4 +1,4 @@ -""" Problem Statement (Digit Fifth Powers): https://projecteuler.net/problem=30 +"""Problem Statement (Digit Fifth Powers): https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: @@ -21,7 +21,6 @@ So, number > 999 and hence a number between 1000 and 1000000 """ - DIGITS_FIFTH_POWER = {str(digit): digit**5 for digit in range(10)} diff --git a/project_euler/problem_032/sol32.py b/project_euler/problem_032/sol32.py index c4d11e86..a402b558 100644 --- a/project_euler/problem_032/sol32.py +++ b/project_euler/problem_032/sol32.py @@ -12,6 +12,7 @@ be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. """ + import itertools diff --git a/project_euler/problem_033/sol1.py b/project_euler/problem_033/sol1.py index 32be424b..187fd61b 100644 --- a/project_euler/problem_033/sol1.py +++ b/project_euler/problem_033/sol1.py @@ -14,6 +14,7 @@ and denominator. If the product of these four fractions is given in its lowest common terms, find the value of the denominator. """ + from __future__ import annotations from fractions import Fraction diff --git a/project_euler/problem_035/sol1.py b/project_euler/problem_035/sol1.py index 644c992e..cf9f6821 100644 --- a/project_euler/problem_035/sol1.py +++ b/project_euler/problem_035/sol1.py @@ -15,6 +15,7 @@ below 1 million using the Sieve of Eratosthenes. Then, out of all these primes, we will rule out the numbers which contain an even digit. After this we will generate each circular combination of the number and check if all are prime. """ + from __future__ import annotations sieve = [True] * 1000001 diff --git a/project_euler/problem_036/sol1.py b/project_euler/problem_036/sol1.py index 1d27356e..3865b2a3 100644 --- a/project_euler/problem_036/sol1.py +++ b/project_euler/problem_036/sol1.py @@ -14,6 +14,7 @@ base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ + from __future__ import annotations diff --git a/project_euler/problem_038/sol1.py b/project_euler/problem_038/sol1.py index e4a6d09f..5bef273e 100644 --- a/project_euler/problem_038/sol1.py +++ b/project_euler/problem_038/sol1.py @@ -37,6 +37,7 @@ a has 3 digits, etc... => 100 <= a < 334, candidate = a * 10^6 + 2a * 10^3 + 3a = 1002003 * a """ + from __future__ import annotations diff --git a/project_euler/problem_041/sol1.py b/project_euler/problem_041/sol1.py index 2ef01206..0c37f546 100644 --- a/project_euler/problem_041/sol1.py +++ b/project_euler/problem_041/sol1.py @@ -10,6 +10,7 @@ All pandigital numbers except for 1, 4 ,7 pandigital numbers are divisible by 3. So we will check only 7 digit pandigital numbers to obtain the largest possible pandigital prime. """ + from __future__ import annotations import math diff --git a/project_euler/problem_042/solution42.py b/project_euler/problem_042/solution42.py index f8a54e40..f678bcde 100644 --- a/project_euler/problem_042/solution42.py +++ b/project_euler/problem_042/solution42.py @@ -13,6 +13,7 @@ Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? """ + import os # Precomputes a list of the 100 first triangular numbers diff --git a/project_euler/problem_043/sol1.py b/project_euler/problem_043/sol1.py index c533f40d..f3a2c71e 100644 --- a/project_euler/problem_043/sol1.py +++ b/project_euler/problem_043/sol1.py @@ -18,7 +18,6 @@ d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. """ - from itertools import permutations diff --git a/project_euler/problem_050/sol1.py b/project_euler/problem_050/sol1.py index fc6e6f2b..0a5f861f 100644 --- a/project_euler/problem_050/sol1.py +++ b/project_euler/problem_050/sol1.py @@ -15,6 +15,7 @@ contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ + from __future__ import annotations diff --git a/project_euler/problem_051/sol1.py b/project_euler/problem_051/sol1.py index 921704bc..dc740c8b 100644 --- a/project_euler/problem_051/sol1.py +++ b/project_euler/problem_051/sol1.py @@ -15,6 +15,7 @@ with this property. Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family. """ + from __future__ import annotations from collections import Counter diff --git a/project_euler/problem_053/sol1.py b/project_euler/problem_053/sol1.py index 0692bbe0..a32b73c5 100644 --- a/project_euler/problem_053/sol1.py +++ b/project_euler/problem_053/sol1.py @@ -16,6 +16,7 @@ It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066. How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than one-million? """ + from math import factorial diff --git a/project_euler/problem_054/sol1.py b/project_euler/problem_054/sol1.py index 86dfa5ed..66aa3a08 100644 --- a/project_euler/problem_054/sol1.py +++ b/project_euler/problem_054/sol1.py @@ -40,6 +40,7 @@ Similar problem on codewars: https://www.codewars.com/kata/ranking-poker-hands https://www.codewars.com/kata/sortable-poker-hands """ + from __future__ import annotations import os diff --git a/project_euler/problem_058/sol1.py b/project_euler/problem_058/sol1.py index 6a991c58..1d2f406e 100644 --- a/project_euler/problem_058/sol1.py +++ b/project_euler/problem_058/sol1.py @@ -33,6 +33,7 @@ So we check individually each one of these before incrementing our count of current primes. """ + import math diff --git a/project_euler/problem_059/sol1.py b/project_euler/problem_059/sol1.py index b795dd24..65bfd3f0 100644 --- a/project_euler/problem_059/sol1.py +++ b/project_euler/problem_059/sol1.py @@ -25,6 +25,7 @@ file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text. """ + from __future__ import annotations import string diff --git a/project_euler/problem_067/sol1.py b/project_euler/problem_067/sol1.py index 2b41fedc..171ff8c2 100644 --- a/project_euler/problem_067/sol1.py +++ b/project_euler/problem_067/sol1.py @@ -11,6 +11,7 @@ Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ + import os diff --git a/project_euler/problem_067/sol2.py b/project_euler/problem_067/sol2.py index 2e88a571..4fb093d4 100644 --- a/project_euler/problem_067/sol2.py +++ b/project_euler/problem_067/sol2.py @@ -11,6 +11,7 @@ Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ + import os diff --git a/project_euler/problem_070/sol1.py b/project_euler/problem_070/sol1.py index f1114a28..9874b741 100644 --- a/project_euler/problem_070/sol1.py +++ b/project_euler/problem_070/sol1.py @@ -28,6 +28,7 @@ References: Finding totients https://en.wikipedia.org/wiki/Euler's_totient_function#Euler's_product_formula """ + from __future__ import annotations import numpy as np diff --git a/project_euler/problem_074/sol1.py b/project_euler/problem_074/sol1.py index a257d4d9..91440b3f 100644 --- a/project_euler/problem_074/sol1.py +++ b/project_euler/problem_074/sol1.py @@ -27,7 +27,6 @@ How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? """ - DIGIT_FACTORIALS = { "0": 1, "1": 1, diff --git a/project_euler/problem_074/sol2.py b/project_euler/problem_074/sol2.py index b54bc023..52a996bf 100644 --- a/project_euler/problem_074/sol2.py +++ b/project_euler/problem_074/sol2.py @@ -33,6 +33,7 @@ The generation of the chain stops before a repeating item or if the size of the is greater then the desired one. After generating each chain, the length is checked and the counter increases. """ + from math import factorial DIGIT_FACTORIAL: dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} diff --git a/project_euler/problem_077/sol1.py b/project_euler/problem_077/sol1.py index 6098ea9e..e8f4e979 100644 --- a/project_euler/problem_077/sol1.py +++ b/project_euler/problem_077/sol1.py @@ -12,6 +12,7 @@ It is possible to write ten as the sum of primes in exactly five different ways: What is the first value which can be written as the sum of primes in over five thousand different ways? """ + from __future__ import annotations from functools import lru_cache diff --git a/project_euler/problem_079/sol1.py b/project_euler/problem_079/sol1.py index d34adcd2..74392e9b 100644 --- a/project_euler/problem_079/sol1.py +++ b/project_euler/problem_079/sol1.py @@ -13,6 +13,7 @@ The text file, keylog.txt, contains fifty successful login attempts. Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible secret passcode of unknown length. """ + import itertools from pathlib import Path diff --git a/project_euler/problem_080/sol1.py b/project_euler/problem_080/sol1.py index 916998bd..8cfcbd41 100644 --- a/project_euler/problem_080/sol1.py +++ b/project_euler/problem_080/sol1.py @@ -6,6 +6,7 @@ the digital sums of the first one hundred decimal digits for all the irrational square roots. Time: 5 October 2020, 18:30 """ + import decimal diff --git a/project_euler/problem_081/sol1.py b/project_euler/problem_081/sol1.py index aef6106b..293027bd 100644 --- a/project_euler/problem_081/sol1.py +++ b/project_euler/problem_081/sol1.py @@ -13,6 +13,7 @@ Find the minimal path sum from the top left to the bottom right by only moving r and down in matrix.txt (https://projecteuler.net/project/resources/p081_matrix.txt), a 31K text file containing an 80 by 80 matrix. """ + import os diff --git a/project_euler/problem_085/sol1.py b/project_euler/problem_085/sol1.py index d0f29796..d0b361ee 100644 --- a/project_euler/problem_085/sol1.py +++ b/project_euler/problem_085/sol1.py @@ -44,6 +44,7 @@ Solution: Reference: https://en.wikipedia.org/wiki/Triangular_number https://en.wikipedia.org/wiki/Quadratic_formula """ + from __future__ import annotations from math import ceil, floor, sqrt diff --git a/project_euler/problem_086/sol1.py b/project_euler/problem_086/sol1.py index 064af215..cbd2b648 100644 --- a/project_euler/problem_086/sol1.py +++ b/project_euler/problem_086/sol1.py @@ -66,7 +66,6 @@ Solution: """ - from math import sqrt diff --git a/project_euler/problem_091/sol1.py b/project_euler/problem_091/sol1.py index 6c9aa3fa..7db98fca 100644 --- a/project_euler/problem_091/sol1.py +++ b/project_euler/problem_091/sol1.py @@ -11,7 +11,6 @@ when each coordinate lies between 0 and 2 inclusive; that is, Given that 0 ≤ x1, y1, x2, y2 ≤ 50, how many right triangles can be formed? """ - from itertools import combinations, product diff --git a/project_euler/problem_101/sol1.py b/project_euler/problem_101/sol1.py index d5c503af..2d209333 100644 --- a/project_euler/problem_101/sol1.py +++ b/project_euler/problem_101/sol1.py @@ -41,6 +41,7 @@ Consider the following tenth degree polynomial generating function: Find the sum of FITs for the BOPs. """ + from __future__ import annotations from collections.abc import Callable diff --git a/project_euler/problem_102/sol1.py b/project_euler/problem_102/sol1.py index 4f6e6361..85fe5eac 100644 --- a/project_euler/problem_102/sol1.py +++ b/project_euler/problem_102/sol1.py @@ -18,6 +18,7 @@ the number of triangles for which the interior contains the origin. NOTE: The first two examples in the file represent the triangles in the example given above. """ + from __future__ import annotations from pathlib import Path diff --git a/project_euler/problem_107/sol1.py b/project_euler/problem_107/sol1.py index 4659eac2..3fe75909 100644 --- a/project_euler/problem_107/sol1.py +++ b/project_euler/problem_107/sol1.py @@ -27,6 +27,7 @@ Solution: We use Prim's algorithm to find a Minimum Spanning Tree. Reference: https://en.wikipedia.org/wiki/Prim%27s_algorithm """ + from __future__ import annotations import os diff --git a/project_euler/problem_123/sol1.py b/project_euler/problem_123/sol1.py index f74cdd99..7239e13a 100644 --- a/project_euler/problem_123/sol1.py +++ b/project_euler/problem_123/sol1.py @@ -37,6 +37,7 @@ So it could be simplified as, r = 2pn when n is odd r = 2 when n is even. """ + from __future__ import annotations from collections.abc import Generator diff --git a/project_euler/problem_144/sol1.py b/project_euler/problem_144/sol1.py index b5f103b6..bc16bf98 100644 --- a/project_euler/problem_144/sol1.py +++ b/project_euler/problem_144/sol1.py @@ -29,7 +29,6 @@ The animation on the right shows the first 10 reflections of the beam. How many times does the beam hit the internal surface of the white cell before exiting? """ - from math import isclose, sqrt diff --git a/project_euler/problem_145/sol1.py b/project_euler/problem_145/sol1.py index 71b85117..ce443828 100644 --- a/project_euler/problem_145/sol1.py +++ b/project_euler/problem_145/sol1.py @@ -13,6 +13,7 @@ There are 120 reversible numbers below one-thousand. How many reversible numbers are there below one-billion (10^9)? """ + EVEN_DIGITS = [0, 2, 4, 6, 8] ODD_DIGITS = [1, 3, 5, 7, 9] diff --git a/project_euler/problem_173/sol1.py b/project_euler/problem_173/sol1.py index 5416e254..9235d00e 100644 --- a/project_euler/problem_173/sol1.py +++ b/project_euler/problem_173/sol1.py @@ -11,7 +11,6 @@ possible to form forty-one different square laminae. Using up to one million tiles how many different square laminae can be formed? """ - from math import ceil, sqrt diff --git a/project_euler/problem_180/sol1.py b/project_euler/problem_180/sol1.py index 12e34dca..72baed42 100644 --- a/project_euler/problem_180/sol1.py +++ b/project_euler/problem_180/sol1.py @@ -44,6 +44,7 @@ we get the right numerator and denominator. Reference: https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem """ + from __future__ import annotations from fractions import Fraction diff --git a/project_euler/problem_191/sol1.py b/project_euler/problem_191/sol1.py index 6bff9d54..efb2a5d0 100644 --- a/project_euler/problem_191/sol1.py +++ b/project_euler/problem_191/sol1.py @@ -25,7 +25,6 @@ References: https://projecteuler.net/problem=191 """ - cache: dict[tuple[int, int, int], int] = {} diff --git a/project_euler/problem_203/sol1.py b/project_euler/problem_203/sol1.py index da943624..8ad089ec 100644 --- a/project_euler/problem_203/sol1.py +++ b/project_euler/problem_203/sol1.py @@ -27,6 +27,7 @@ Pascal's triangle. References: - https://en.wikipedia.org/wiki/Pascal%27s_triangle """ + from __future__ import annotations diff --git a/project_euler/problem_551/sol1.py b/project_euler/problem_551/sol1.py index 2cd75efb..100e9d41 100644 --- a/project_euler/problem_551/sol1.py +++ b/project_euler/problem_551/sol1.py @@ -12,7 +12,6 @@ You are given a(10^6) = 31054319. Find a(10^15) """ - ks = range(2, 20 + 1) base = [10**k for k in range(ks[-1] + 1)] memo: dict[int, dict[int, list[list[int]]]] = {} diff --git a/scheduling/highest_response_ratio_next.py b/scheduling/highest_response_ratio_next.py index 057bd64c..112c2a85 100644 --- a/scheduling/highest_response_ratio_next.py +++ b/scheduling/highest_response_ratio_next.py @@ -4,6 +4,7 @@ It was developed as modification of shortest job next or shortest job first (SJN to mitigate the problem of process starvation. https://en.wikipedia.org/wiki/Highest_response_ratio_next """ + from statistics import mean import numpy as np diff --git a/scheduling/job_sequence_with_deadline.py b/scheduling/job_sequence_with_deadline.py index fccb49cd..ee1fdbd0 100644 --- a/scheduling/job_sequence_with_deadline.py +++ b/scheduling/job_sequence_with_deadline.py @@ -13,6 +13,7 @@ This problem can be solved using the concept of "GREEDY ALGORITHM". Time Complexity - O(n log n) https://medium.com/@nihardudhat2000/job-sequencing-with-deadline-17ddbb5890b5 """ + from dataclasses import dataclass from operator import attrgetter diff --git a/scheduling/non_preemptive_shortest_job_first.py b/scheduling/non_preemptive_shortest_job_first.py index 69c974b0..cb7ffd3a 100644 --- a/scheduling/non_preemptive_shortest_job_first.py +++ b/scheduling/non_preemptive_shortest_job_first.py @@ -5,7 +5,6 @@ https://www.guru99.com/shortest-job-first-sjf-scheduling.html https://en.wikipedia.org/wiki/Shortest_job_next """ - from __future__ import annotations from statistics import mean diff --git a/scheduling/round_robin.py b/scheduling/round_robin.py index e8d54dd9..5f6c7f34 100644 --- a/scheduling/round_robin.py +++ b/scheduling/round_robin.py @@ -3,6 +3,7 @@ Round Robin is a scheduling algorithm. In Round Robin each process is assigned a fixed time slot in a cyclic way. https://en.wikipedia.org/wiki/Round-robin_scheduling """ + from __future__ import annotations from statistics import mean diff --git a/scheduling/shortest_job_first.py b/scheduling/shortest_job_first.py index 871de820..cfd0417e 100644 --- a/scheduling/shortest_job_first.py +++ b/scheduling/shortest_job_first.py @@ -3,6 +3,7 @@ Shortest job remaining first Please note arrival time and burst Please use spaces to separate times entered. """ + from __future__ import annotations import pandas as pd diff --git a/searches/binary_search.py b/searches/binary_search.py index 586be39c..2e66b672 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -9,6 +9,7 @@ python3 -m doctest -v binary_search.py For manual testing run: python3 binary_search.py """ + from __future__ import annotations import bisect diff --git a/searches/binary_tree_traversal.py b/searches/binary_tree_traversal.py index 6fb841af..4897ef17 100644 --- a/searches/binary_tree_traversal.py +++ b/searches/binary_tree_traversal.py @@ -1,6 +1,7 @@ """ This is pure Python implementation of tree traversal algorithms """ + from __future__ import annotations import queue diff --git a/searches/fibonacci_search.py b/searches/fibonacci_search.py index 55fc05d3..ec3dfa7f 100644 --- a/searches/fibonacci_search.py +++ b/searches/fibonacci_search.py @@ -10,6 +10,7 @@ python3 -m doctest -v fibonacci_search.py For manual testing run: python3 fibonacci_search.py """ + from functools import lru_cache diff --git a/searches/jump_search.py b/searches/jump_search.py index 3bc3c378..e72d85e8 100644 --- a/searches/jump_search.py +++ b/searches/jump_search.py @@ -14,8 +14,7 @@ from typing import Any, Protocol, TypeVar class Comparable(Protocol): - def __lt__(self, other: Any, /) -> bool: - ... + def __lt__(self, other: Any, /) -> bool: ... T = TypeVar("T", bound=Comparable) diff --git a/searches/quick_select.py b/searches/quick_select.py index 5ede8c4d..c8282e1f 100644 --- a/searches/quick_select.py +++ b/searches/quick_select.py @@ -4,6 +4,7 @@ calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted https://en.wikipedia.org/wiki/Quickselect """ + import random diff --git a/searches/simple_binary_search.py b/searches/simple_binary_search.py index ff043d73..00e83ff9 100644 --- a/searches/simple_binary_search.py +++ b/searches/simple_binary_search.py @@ -7,6 +7,7 @@ python3 -m doctest -v simple_binary_search.py For manual testing run: python3 simple_binary_search.py """ + from __future__ import annotations diff --git a/searches/tabu_search.py b/searches/tabu_search.py index d998ddc5..fd482a81 100644 --- a/searches/tabu_search.py +++ b/searches/tabu_search.py @@ -24,6 +24,7 @@ python tabu_search.py -f your_file_name.txt -number_of_iterations_of_tabu_search -s size_of_tabu_search e.g. python tabu_search.py -f tabudata2.txt -i 4 -s 3 """ + import argparse import copy diff --git a/searches/ternary_search.py b/searches/ternary_search.py index cb36e72f..8dcd6b5b 100644 --- a/searches/ternary_search.py +++ b/searches/ternary_search.py @@ -6,6 +6,7 @@ This is a type of divide and conquer algorithm which divides the search space in Time Complexity : O(log3 N) Space Complexity : O(1) """ + from __future__ import annotations # This is the precision for this function which can be altered. diff --git a/sorts/bitonic_sort.py b/sorts/bitonic_sort.py index b65f877a..600f8139 100644 --- a/sorts/bitonic_sort.py +++ b/sorts/bitonic_sort.py @@ -3,6 +3,7 @@ Python program for Bitonic Sort. Note that this program works only when size of input is a power of 2. """ + from __future__ import annotations diff --git a/sorts/bucket_sort.py b/sorts/bucket_sort.py index c016e9e2..1c1320a5 100644 --- a/sorts/bucket_sort.py +++ b/sorts/bucket_sort.py @@ -27,6 +27,7 @@ If k = O(n), time complexity is O(n) Source: https://en.wikipedia.org/wiki/Bucket_sort """ + from __future__ import annotations diff --git a/sorts/dutch_national_flag_sort.py b/sorts/dutch_national_flag_sort.py index 758e3a88..b4f1665c 100644 --- a/sorts/dutch_national_flag_sort.py +++ b/sorts/dutch_national_flag_sort.py @@ -23,7 +23,6 @@ For manual testing run: python dnf_sort.py """ - # Python program to sort a sequence containing only 0, 1 and 2 in a single pass. red = 0 # The first color of the flag. white = 1 # The second color of the flag. diff --git a/sorts/insertion_sort.py b/sorts/insertion_sort.py index f11ddac3..46b263d8 100644 --- a/sorts/insertion_sort.py +++ b/sorts/insertion_sort.py @@ -18,8 +18,7 @@ from typing import Any, Protocol, TypeVar class Comparable(Protocol): - def __lt__(self, other: Any, /) -> bool: - ... + def __lt__(self, other: Any, /) -> bool: ... T = TypeVar("T", bound=Comparable) diff --git a/sorts/intro_sort.py b/sorts/intro_sort.py index 5a5741dc..1184b381 100644 --- a/sorts/intro_sort.py +++ b/sorts/intro_sort.py @@ -3,6 +3,7 @@ Introspective Sort is a hybrid sort (Quick Sort + Heap Sort + Insertion Sort) if the size of the list is under 16, use insertion sort https://en.wikipedia.org/wiki/Introsort """ + import math diff --git a/sorts/msd_radix_sort.py b/sorts/msd_radix_sort.py index 03f84c75..6aba4263 100644 --- a/sorts/msd_radix_sort.py +++ b/sorts/msd_radix_sort.py @@ -4,6 +4,7 @@ It used the binary representation of the integers to sort them. https://en.wikipedia.org/wiki/Radix_sort """ + from __future__ import annotations diff --git a/sorts/odd_even_transposition_parallel.py b/sorts/odd_even_transposition_parallel.py index b8ab46df..9d2bcdbd 100644 --- a/sorts/odd_even_transposition_parallel.py +++ b/sorts/odd_even_transposition_parallel.py @@ -10,6 +10,7 @@ comparisons. They are synchronized with locks and message passing but other forms of synchronization could be used. """ + from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time diff --git a/sorts/pigeon_sort.py b/sorts/pigeon_sort.py index 3e6d4c09..fdfa692f 100644 --- a/sorts/pigeon_sort.py +++ b/sorts/pigeon_sort.py @@ -1,14 +1,15 @@ """ - This is an implementation of Pigeon Hole Sort. - For doctests run following command: +This is an implementation of Pigeon Hole Sort. +For doctests run following command: - python3 -m doctest -v pigeon_sort.py - or - python -m doctest -v pigeon_sort.py +python3 -m doctest -v pigeon_sort.py +or +python -m doctest -v pigeon_sort.py - For manual testing run: - python pigeon_sort.py +For manual testing run: +python pigeon_sort.py """ + from __future__ import annotations diff --git a/sorts/quick_sort.py b/sorts/quick_sort.py index 6b95fc14..374d52e7 100644 --- a/sorts/quick_sort.py +++ b/sorts/quick_sort.py @@ -7,6 +7,7 @@ python3 -m doctest -v quick_sort.py For manual testing run: python3 quick_sort.py """ + from __future__ import annotations from random import randrange diff --git a/sorts/radix_sort.py b/sorts/radix_sort.py index 832b6162..1dbf5fbd 100644 --- a/sorts/radix_sort.py +++ b/sorts/radix_sort.py @@ -3,6 +3,7 @@ This is a pure Python implementation of the radix sort algorithm Source: https://en.wikipedia.org/wiki/Radix_sort """ + from __future__ import annotations RADIX = 10 diff --git a/sorts/recursive_insertion_sort.py b/sorts/recursive_insertion_sort.py index 297dbe94..93465350 100644 --- a/sorts/recursive_insertion_sort.py +++ b/sorts/recursive_insertion_sort.py @@ -1,6 +1,7 @@ """ A recursive implementation of the insertion sort algorithm """ + from __future__ import annotations diff --git a/sorts/slowsort.py b/sorts/slowsort.py index a5f4e873..394e6eed 100644 --- a/sorts/slowsort.py +++ b/sorts/slowsort.py @@ -8,6 +8,7 @@ in their paper Pessimal Algorithms and Simplexity Analysis Source: https://en.wikipedia.org/wiki/Slowsort """ + from __future__ import annotations diff --git a/sorts/tree_sort.py b/sorts/tree_sort.py index dc95856f..05686495 100644 --- a/sorts/tree_sort.py +++ b/sorts/tree_sort.py @@ -3,6 +3,7 @@ Tree_sort algorithm. Build a Binary Search Tree and then iterate thru it to get a sorted list. """ + from __future__ import annotations from collections.abc import Iterator diff --git a/strings/boyer_moore_search.py b/strings/boyer_moore_search.py index 117305d3..9615d2fd 100644 --- a/strings/boyer_moore_search.py +++ b/strings/boyer_moore_search.py @@ -17,6 +17,7 @@ Time Complexity : O(n/m) n=length of main string m=length of pattern string """ + from __future__ import annotations diff --git a/strings/check_anagrams.py b/strings/check_anagrams.py index 9dcdffcf..d747368b 100644 --- a/strings/check_anagrams.py +++ b/strings/check_anagrams.py @@ -1,6 +1,7 @@ """ wiki: https://en.wikipedia.org/wiki/Anagram """ + from collections import defaultdict diff --git a/strings/top_k_frequent_words.py b/strings/top_k_frequent_words.py index f3d1e0cd..40fa7fc8 100644 --- a/strings/top_k_frequent_words.py +++ b/strings/top_k_frequent_words.py @@ -13,7 +13,6 @@ def top_k_frequent_words(words, k_value): return [x[0] for x in Counter(words).most_common(k_value)] """ - from collections import Counter from functools import total_ordering diff --git a/web_programming/co2_emission.py b/web_programming/co2_emission.py index 97927e7e..88a426cb 100644 --- a/web_programming/co2_emission.py +++ b/web_programming/co2_emission.py @@ -1,6 +1,7 @@ """ Get CO2 emission data from the UK CarbonIntensity API """ + from datetime import date import requests diff --git a/web_programming/emails_from_url.py b/web_programming/emails_from_url.py index 074ef878..6b4bacfe 100644 --- a/web_programming/emails_from_url.py +++ b/web_programming/emails_from_url.py @@ -1,4 +1,5 @@ """Get the site emails from URL.""" + from __future__ import annotations __author__ = "Muhammad Umer Farooq" diff --git a/web_programming/fetch_github_info.py b/web_programming/fetch_github_info.py index aa4e1d7b..7a4985b6 100644 --- a/web_programming/fetch_github_info.py +++ b/web_programming/fetch_github_info.py @@ -17,6 +17,7 @@ with your token:: #!/usr/bin/env bash export USER_TOKEN="" """ + from __future__ import annotations import os diff --git a/web_programming/fetch_jobs.py b/web_programming/fetch_jobs.py index 5af90a0b..49abd3c8 100644 --- a/web_programming/fetch_jobs.py +++ b/web_programming/fetch_jobs.py @@ -1,6 +1,7 @@ """ Scraping jobs given job title and location from indeed website """ + from __future__ import annotations from collections.abc import Generator diff --git a/web_programming/get_amazon_product_data.py b/web_programming/get_amazon_product_data.py index a1617568..c2f2ac5a 100644 --- a/web_programming/get_amazon_product_data.py +++ b/web_programming/get_amazon_product_data.py @@ -4,7 +4,6 @@ and fetch from Amazon information about products of this name or category. The information will include title, URL, price, ratings, and the discount available. """ - from itertools import zip_longest import requests diff --git a/web_programming/recaptcha_verification.py b/web_programming/recaptcha_verification.py index 47c6c42f..b03afb28 100644 --- a/web_programming/recaptcha_verification.py +++ b/web_programming/recaptcha_verification.py @@ -31,6 +31,7 @@ SecretKey should be kept in your site's back end Below a Django function for the views.py file contains a login form for demonstrating recaptcha verification. """ + import requests try: diff --git a/web_programming/search_books_by_isbn.py b/web_programming/search_books_by_isbn.py index d5d4cfe9..07429e9a 100644 --- a/web_programming/search_books_by_isbn.py +++ b/web_programming/search_books_by_isbn.py @@ -3,6 +3,7 @@ Get book and author data from https://openlibrary.org ISBN: https://en.wikipedia.org/wiki/International_Standard_Book_Number """ + from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests