diff --git a/.github/workflows/autoblack.yml b/.github/workflows/autoblack.yml index 25a04f2767c8..25d291c6ffbb 100644 --- a/.github/workflows/autoblack.yml +++ b/.github/workflows/autoblack.yml @@ -17,7 +17,7 @@ jobs: if: failure() run: | black . - isort --profile black --recursive . + isort --profile black . git config --global user.name github-actions git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY diff --git a/DIRECTORY.md b/DIRECTORY.md index 34ee376be1c3..17940c6a333b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -253,6 +253,7 @@ * [Finding Bridges](https://github.com/TheAlgorithms/Python/blob/master/graphs/finding_bridges.py) * [Frequent Pattern Graph Miner](https://github.com/TheAlgorithms/Python/blob/master/graphs/frequent_pattern_graph_miner.py) * [G Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/graphs/g_topological_sort.py) + * [Gale Shapley Bigraph](https://github.com/TheAlgorithms/Python/blob/master/graphs/gale_shapley_bigraph.py) * [Graph List](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_list.py) * [Graph Matrix](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_matrix.py) * [Graphs Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/graphs/graphs_floyd_warshall.py) @@ -596,6 +597,7 @@ ## Searches * [Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_search.py) + * [Double Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search.py) * [Fibonacci Search](https://github.com/TheAlgorithms/Python/blob/master/searches/fibonacci_search.py) * [Hill Climbing](https://github.com/TheAlgorithms/Python/blob/master/searches/hill_climbing.py) * [Interpolation Search](https://github.com/TheAlgorithms/Python/blob/master/searches/interpolation_search.py) diff --git a/arithmetic_analysis/in_static_equilibrium.py b/arithmetic_analysis/in_static_equilibrium.py index addaff888f7f..dd7fa706143e 100644 --- a/arithmetic_analysis/in_static_equilibrium.py +++ b/arithmetic_analysis/in_static_equilibrium.py @@ -6,9 +6,10 @@ mypy : passed """ -from numpy import array, cos, sin, radians, cross # type: ignore from typing import List +from numpy import array, cos, cross, radians, sin # type: ignore + def polar_force( magnitude: float, angle: float, radian_mode: bool = False diff --git a/arithmetic_analysis/newton_raphson.py b/arithmetic_analysis/newton_raphson.py index a3e8bbf0fc21..890cff060ec8 100644 --- a/arithmetic_analysis/newton_raphson.py +++ b/arithmetic_analysis/newton_raphson.py @@ -2,9 +2,9 @@ # Author: Syed Haseeb Shah (github.com/QuantumNovice) # The Newton-Raphson method (also known as Newton's method) is a way to # quickly find a good approximation for the root of a real-valued function - from decimal import Decimal from math import * # noqa: F401, F403 + from sympy import diff diff --git a/ciphers/hill_cipher.py b/ciphers/hill_cipher.py index 82382d873baf..0014c8693bc6 100644 --- a/ciphers/hill_cipher.py +++ b/ciphers/hill_cipher.py @@ -35,8 +35,8 @@ https://www.youtube.com/watch?v=4RhLNDqcjpA """ - import string + import numpy diff --git a/ciphers/playfair_cipher.py b/ciphers/playfair_cipher.py index 030fe8155a69..33b52906fb05 100644 --- a/ciphers/playfair_cipher.py +++ b/ciphers/playfair_cipher.py @@ -1,5 +1,5 @@ -import string import itertools +import string def chunker(seq, size): diff --git a/compression/burrows_wheeler.py b/compression/burrows_wheeler.py index 2a08c6092cda..03912f80e1a7 100644 --- a/compression/burrows_wheeler.py +++ b/compression/burrows_wheeler.py @@ -10,7 +10,7 @@ original character. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. """ -from typing import List, Dict +from typing import Dict, List def all_rotations(s: str) -> List[str]: diff --git a/computer_vision/harriscorner.py b/computer_vision/harriscorner.py index 35302f01411b..fb7f560f7873 100644 --- a/computer_vision/harriscorner.py +++ b/computer_vision/harriscorner.py @@ -1,5 +1,5 @@ -import numpy as np import cv2 +import numpy as np """ Harris Corner Detector diff --git a/data_structures/binary_tree/non_recursive_segment_tree.py b/data_structures/binary_tree/non_recursive_segment_tree.py index 97851af937d9..cdcf1fa8dd2d 100644 --- a/data_structures/binary_tree/non_recursive_segment_tree.py +++ b/data_structures/binary_tree/non_recursive_segment_tree.py @@ -35,7 +35,7 @@ >>> st.query(0, 2) [1, 2, 3] """ -from typing import List, Callable, TypeVar +from typing import Callable, List, TypeVar T = TypeVar("T") diff --git a/data_structures/binary_tree/segment_tree_other.py b/data_structures/binary_tree/segment_tree_other.py index c3ab493d5f4f..df98eeffb3c6 100644 --- a/data_structures/binary_tree/segment_tree_other.py +++ b/data_structures/binary_tree/segment_tree_other.py @@ -3,9 +3,8 @@ allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ - -from queue import Queue from collections.abc import Sequence +from queue import Queue class SegmentTreeNode(object): diff --git a/data_structures/hashing/double_hash.py b/data_structures/hashing/double_hash.py index ce4454db0bef..9c6c8fed6a00 100644 --- a/data_structures/hashing/double_hash.py +++ b/data_structures/hashing/double_hash.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 - from hash_table import HashTable -from number_theory.prime_numbers import next_prime, check_prime +from number_theory.prime_numbers import check_prime, next_prime class DoubleHash(HashTable): diff --git a/data_structures/hashing/hash_table_with_linked_list.py b/data_structures/hashing/hash_table_with_linked_list.py index 48d93bbc5cff..94934e37b65e 100644 --- a/data_structures/hashing/hash_table_with_linked_list.py +++ b/data_structures/hashing/hash_table_with_linked_list.py @@ -1,6 +1,7 @@ -from hash_table import HashTable from collections import deque +from hash_table import HashTable + class HashTableWithLinkedList(HashTable): def __init__(self, *args, **kwargs): diff --git a/digital_image_processing/convert_to_negative.py b/digital_image_processing/convert_to_negative.py index cba503938aec..7df44138973c 100644 --- a/digital_image_processing/convert_to_negative.py +++ b/digital_image_processing/convert_to_negative.py @@ -1,8 +1,7 @@ """ Implemented an algorithm using opencv to convert a colored image into its negative """ - -from cv2 import imread, imshow, waitKey, destroyAllWindows +from cv2 import destroyAllWindows, imread, imshow, waitKey def convert_to_negative(img): diff --git a/digital_image_processing/dithering/burkes.py b/digital_image_processing/dithering/burkes.py index 0de21f4c009b..2bf0bbe03225 100644 --- a/digital_image_processing/dithering/burkes.py +++ b/digital_image_processing/dithering/burkes.py @@ -1,8 +1,8 @@ """ Implementation Burke's algorithm (dithering) """ -from cv2 import destroyAllWindows, imread, imshow, waitKey import numpy as np +from cv2 import destroyAllWindows, imread, imshow, waitKey class Burkes: diff --git a/digital_image_processing/edge_detection/canny.py b/digital_image_processing/edge_detection/canny.py index 477ffcb9bbb1..295b4d825c12 100644 --- a/digital_image_processing/edge_detection/canny.py +++ b/digital_image_processing/edge_detection/canny.py @@ -1,5 +1,6 @@ import cv2 import numpy as np + from digital_image_processing.filters.convolve import img_convolve from digital_image_processing.filters.sobel_filter import sobel_filter diff --git a/digital_image_processing/filters/bilateral_filter.py b/digital_image_processing/filters/bilateral_filter.py index 753d6ddb7a3f..76ae4dd20345 100644 --- a/digital_image_processing/filters/bilateral_filter.py +++ b/digital_image_processing/filters/bilateral_filter.py @@ -9,11 +9,11 @@ Output: img:A 2d zero padded image with values in between 0 and 1 """ +import math +import sys import cv2 import numpy as np -import math -import sys def vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray: diff --git a/digital_image_processing/filters/convolve.py b/digital_image_processing/filters/convolve.py index ec500d940366..299682010da6 100644 --- a/digital_image_processing/filters/convolve.py +++ b/digital_image_processing/filters/convolve.py @@ -1,8 +1,8 @@ # @Author : lightXu # @File : convolve.py # @Time : 2019/7/8 0008 下午 16:13 -from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey -from numpy import array, zeros, ravel, pad, dot, uint8 +from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey +from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): diff --git a/digital_image_processing/filters/gaussian_filter.py b/digital_image_processing/filters/gaussian_filter.py index 79026ddcc57a..87fa67fb65ea 100644 --- a/digital_image_processing/filters/gaussian_filter.py +++ b/digital_image_processing/filters/gaussian_filter.py @@ -1,10 +1,11 @@ """ Implementation of gaussian filter algorithm """ -from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey -from numpy import pi, mgrid, exp, square, zeros, ravel, dot, uint8 from itertools import product +from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey +from numpy import dot, exp, mgrid, pi, ravel, square, uint8, zeros + def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 diff --git a/digital_image_processing/filters/median_filter.py b/digital_image_processing/filters/median_filter.py index 151ef8a55df1..174018569d62 100644 --- a/digital_image_processing/filters/median_filter.py +++ b/digital_image_processing/filters/median_filter.py @@ -1,9 +1,8 @@ """ Implementation of median filter algorithm """ - -from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey -from numpy import zeros_like, ravel, sort, multiply, divide, int8 +from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey +from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): diff --git a/digital_image_processing/filters/sobel_filter.py b/digital_image_processing/filters/sobel_filter.py index 822d49fe38a1..33284a32f424 100644 --- a/digital_image_processing/filters/sobel_filter.py +++ b/digital_image_processing/filters/sobel_filter.py @@ -2,7 +2,8 @@ # @File : sobel_filter.py # @Time : 2019/7/8 0008 下午 16:26 import numpy as np -from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey +from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey + from digital_image_processing.filters.convolve import img_convolve diff --git a/digital_image_processing/histogram_equalization/histogram_stretch.py b/digital_image_processing/histogram_equalization/histogram_stretch.py index d4a6c08418ee..0288a2c1fcf5 100644 --- a/digital_image_processing/histogram_equalization/histogram_stretch.py +++ b/digital_image_processing/histogram_equalization/histogram_stretch.py @@ -6,10 +6,9 @@ import copy import os -import numpy as np - import cv2 -import matplotlib.pyplot as plt +import numpy as np +from matplotlib import pyplot as plt class contrastStretch: diff --git a/digital_image_processing/resize/resize.py b/digital_image_processing/resize/resize.py index f33e80e580de..4836521f9f58 100644 --- a/digital_image_processing/resize/resize.py +++ b/digital_image_processing/resize/resize.py @@ -1,6 +1,6 @@ """ Multiple image resizing techniques """ import numpy as np -from cv2 import imread, imshow, waitKey, destroyAllWindows +from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: diff --git a/digital_image_processing/rotation/rotation.py b/digital_image_processing/rotation/rotation.py index 37b45ca39897..2951f18fc0ec 100644 --- a/digital_image_processing/rotation/rotation.py +++ b/digital_image_processing/rotation/rotation.py @@ -1,6 +1,6 @@ -from matplotlib import pyplot as plt -import numpy as np import cv2 +import numpy as np +from matplotlib import pyplot as plt def get_rotation( diff --git a/digital_image_processing/sepia.py b/digital_image_processing/sepia.py index b97b4c0ae1bc..dfb5951676aa 100644 --- a/digital_image_processing/sepia.py +++ b/digital_image_processing/sepia.py @@ -1,8 +1,7 @@ """ Implemented an algorithm using opencv to tone an image with sepia technique """ - -from cv2 import imread, imshow, waitKey, destroyAllWindows +from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): diff --git a/digital_image_processing/test_digital_image_processing.py b/digital_image_processing/test_digital_image_processing.py index fe8890de9a31..40f2f7b83b6d 100644 --- a/digital_image_processing/test_digital_image_processing.py +++ b/digital_image_processing/test_digital_image_processing.py @@ -1,21 +1,21 @@ """ PyTest's for Digital Image Processing """ - -import digital_image_processing.edge_detection.canny as canny -import digital_image_processing.filters.gaussian_filter as gg -import digital_image_processing.filters.median_filter as med -import digital_image_processing.filters.sobel_filter as sob -import digital_image_processing.filters.convolve as conv -import digital_image_processing.change_contrast as cc -import digital_image_processing.convert_to_negative as cn -import digital_image_processing.sepia as sp -import digital_image_processing.dithering.burkes as bs -import digital_image_processing.resize.resize as rs -from cv2 import imread, cvtColor, COLOR_BGR2GRAY +from cv2 import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uint8 from PIL import Image +from digital_image_processing import change_contrast as cc +from digital_image_processing import convert_to_negative as cn +from digital_image_processing import sepia as sp +from digital_image_processing.dithering import burkes as bs +from digital_image_processing.edge_detection import canny as canny +from digital_image_processing.filters import convolve as conv +from digital_image_processing.filters import gaussian_filter as gg +from digital_image_processing.filters import median_filter as med +from digital_image_processing.filters import sobel_filter as sob +from digital_image_processing.resize import resize as rs + img = imread(r"digital_image_processing/image_data/lena_small.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) diff --git a/dynamic_programming/fractional_knapsack.py b/dynamic_programming/fractional_knapsack.py index 15210146bf66..c74af7ef8fc5 100644 --- a/dynamic_programming/fractional_knapsack.py +++ b/dynamic_programming/fractional_knapsack.py @@ -1,5 +1,5 @@ -from itertools import accumulate from bisect import bisect +from itertools import accumulate def fracKnapsack(vl, wt, W, n): diff --git a/dynamic_programming/max_sub_array.py b/dynamic_programming/max_sub_array.py index 284edb5841e4..1ca4f90bbaa2 100644 --- a/dynamic_programming/max_sub_array.py +++ b/dynamic_programming/max_sub_array.py @@ -73,9 +73,10 @@ def max_sub_array(nums: List[int]) -> int: A random simulation of this algorithm. """ import time - import matplotlib.pyplot as plt from random import randint + from matplotlib import pyplot as plt + inputs = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] tim = [] for i in inputs: diff --git a/dynamic_programming/optimal_binary_search_tree.py b/dynamic_programming/optimal_binary_search_tree.py index e6f93f85ef0f..0d94c1b61d39 100644 --- a/dynamic_programming/optimal_binary_search_tree.py +++ b/dynamic_programming/optimal_binary_search_tree.py @@ -16,9 +16,7 @@ # frequencies will be placed near the root of the tree while the nodes # with low frequencies will be placed near the leaves of the tree thus # reducing search time in the most frequent instances. - import sys - from random import randint diff --git a/fuzzy_logic/fuzzy_operations.py b/fuzzy_logic/fuzzy_operations.py index 795a8cde653f..0f573f158663 100644 --- a/fuzzy_logic/fuzzy_operations.py +++ b/fuzzy_logic/fuzzy_operations.py @@ -9,7 +9,6 @@ import numpy as np import skfuzzy as fuzz - if __name__ == "__main__": # Create universe of discourse in Python using linspace () X = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) @@ -45,7 +44,7 @@ # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt plt.figure() diff --git a/geodesy/lamberts_ellipsoidal_distance.py b/geodesy/lamberts_ellipsoidal_distance.py index 969e70befd0b..4a318265e5e6 100644 --- a/geodesy/lamberts_ellipsoidal_distance.py +++ b/geodesy/lamberts_ellipsoidal_distance.py @@ -1,4 +1,5 @@ from math import atan, cos, radians, sin, tan + from haversine_distance import haversine_distance diff --git a/graphics/bezier_curve.py b/graphics/bezier_curve.py index 512efadf86ee..48755647e02d 100644 --- a/graphics/bezier_curve.py +++ b/graphics/bezier_curve.py @@ -1,7 +1,7 @@ # https://en.wikipedia.org/wiki/B%C3%A9zier_curve # https://www.tutorialspoint.com/computer_graphics/computer_graphics_curves.htm - from typing import List, Tuple + from scipy.special import comb @@ -78,7 +78,7 @@ def plot_curve(self, step_size: float = 0.01): step_size: defines the step(s) at which to evaluate the Bezier curve. The smaller the step size, the finer the curve produced. """ - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt to_plot_x: List[float] = [] # x coordinates of points to plot to_plot_y: List[float] = [] # y coordinates of points to plot diff --git a/graphs/basic_graphs.py b/graphs/basic_graphs.py index 1cbd82a2bd08..6e3c63251527 100644 --- a/graphs/basic_graphs.py +++ b/graphs/basic_graphs.py @@ -1,6 +1,5 @@ from collections import deque - if __name__ == "__main__": # Accept No. of Nodes and edges n, m = map(int, input().split(" ")) diff --git a/graphs/breadth_first_search_2.py b/graphs/breadth_first_search_2.py index 0c87b5d8bf3d..293a1012f61f 100644 --- a/graphs/breadth_first_search_2.py +++ b/graphs/breadth_first_search_2.py @@ -12,8 +12,7 @@ mark w as explored add w to Q (at the end) """ - -from typing import Set, Dict +from typing import Dict, Set G = { "A": ["B", "C"], diff --git a/graphs/depth_first_search.py b/graphs/depth_first_search.py index f3e0ed4ebaa6..1e2231907b78 100644 --- a/graphs/depth_first_search.py +++ b/graphs/depth_first_search.py @@ -11,8 +11,7 @@ if v unexplored: DFS(G, v) """ - -from typing import Set, Dict +from typing import Dict, Set def depth_first_search(graph: Dict, start: str) -> Set[int]: diff --git a/graphs/directed_and_undirected_(weighted)_graph.py b/graphs/directed_and_undirected_(weighted)_graph.py index 0312e982a9e0..267111a3a401 100644 --- a/graphs/directed_and_undirected_(weighted)_graph.py +++ b/graphs/directed_and_undirected_(weighted)_graph.py @@ -1,7 +1,7 @@ -from collections import deque -import random as rand import math as math +import random as rand import time +from collections import deque # the default weight is 1 if not assigned but all the implementation is weighted diff --git a/graphs/multi_heuristic_astar.py b/graphs/multi_heuristic_astar.py index 386aab695bb0..77ca5760d5f0 100644 --- a/graphs/multi_heuristic_astar.py +++ b/graphs/multi_heuristic_astar.py @@ -1,4 +1,5 @@ import heapq + import numpy as np diff --git a/greedy_method/test_knapsack.py b/greedy_method/test_knapsack.py index 71a259a1ec46..f3ae624ea7aa 100644 --- a/greedy_method/test_knapsack.py +++ b/greedy_method/test_knapsack.py @@ -1,4 +1,5 @@ import unittest + import greedy_knapsack as kp diff --git a/hashes/sha1.py b/hashes/sha1.py index 26069fb9b7fb..04ecdd788039 100644 --- a/hashes/sha1.py +++ b/hashes/sha1.py @@ -23,10 +23,9 @@ the final hash. Reference: https://deadhacker.com/2006/02/21/sha-1-illustrated/ """ - import argparse -import struct import hashlib # hashlib is only used inside the Test class +import struct import unittest diff --git a/linear_algebra/src/test_linear_algebra.py b/linear_algebra/src/test_linear_algebra.py index 21fed9529ac0..be6245747f87 100644 --- a/linear_algebra/src/test_linear_algebra.py +++ b/linear_algebra/src/test_linear_algebra.py @@ -6,9 +6,16 @@ This file contains the test-suite for the linear algebra library. """ - import unittest -from lib import Matrix, Vector, axpy, squareZeroMatrix, unitBasisVector, zeroVector + +from lib import ( + Matrix, + Vector, + axpy, + squareZeroMatrix, + unitBasisVector, + zeroVector, +) class Test(unittest.TestCase): diff --git a/machine_learning/gaussian_naive_bayes.py b/machine_learning/gaussian_naive_bayes.py index 24c884adb98a..c200aa5a4d2d 100644 --- a/machine_learning/gaussian_naive_bayes.py +++ b/machine_learning/gaussian_naive_bayes.py @@ -1,10 +1,9 @@ # Gaussian Naive Bayes Example - -from sklearn.naive_bayes import GaussianNB -from sklearn.metrics import plot_confusion_matrix +from matplotlib import pyplot as plt from sklearn.datasets import load_iris +from sklearn.metrics import plot_confusion_matrix from sklearn.model_selection import train_test_split -import matplotlib.pyplot as plt +from sklearn.naive_bayes import GaussianNB def main(): diff --git a/machine_learning/k_means_clust.py b/machine_learning/k_means_clust.py index 9f6c65f58fd6..071c58db256b 100644 --- a/machine_learning/k_means_clust.py +++ b/machine_learning/k_means_clust.py @@ -52,11 +52,12 @@ """ +import warnings + import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import pairwise_distances -import warnings warnings.filterwarnings("ignore") @@ -193,7 +194,7 @@ def kmeans( # Mock test below if False: # change to true to run this test case. - import sklearn.datasets as ds + from sklearn import datasets as ds dataset = ds.load_iris() k = 3 diff --git a/machine_learning/k_nearest_neighbours.py b/machine_learning/k_nearest_neighbours.py index 481a8e1dbcd0..e90ea09a58c1 100644 --- a/machine_learning/k_nearest_neighbours.py +++ b/machine_learning/k_nearest_neighbours.py @@ -1,5 +1,6 @@ -import numpy as np from collections import Counter + +import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split diff --git a/machine_learning/knn_sklearn.py b/machine_learning/knn_sklearn.py index c36a530736cd..9a9114102ff3 100644 --- a/machine_learning/knn_sklearn.py +++ b/machine_learning/knn_sklearn.py @@ -1,5 +1,5 @@ -from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris +from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier # Load iris file diff --git a/machine_learning/linear_discriminant_analysis.py b/machine_learning/linear_discriminant_analysis.py index 01be288ea64a..b26da2628982 100644 --- a/machine_learning/linear_discriminant_analysis.py +++ b/machine_learning/linear_discriminant_analysis.py @@ -41,11 +41,9 @@ Author: @EverLookNeverSee """ - from math import log from os import name, system -from random import gauss -from random import seed +from random import gauss, seed # Make a training dataset drawn from a gaussian distribution diff --git a/machine_learning/linear_regression.py b/machine_learning/linear_regression.py index 29bb7c48589e..8c0dfebbca9d 100644 --- a/machine_learning/linear_regression.py +++ b/machine_learning/linear_regression.py @@ -7,8 +7,8 @@ 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 requests import numpy as np +import requests def collect_dataset(): diff --git a/machine_learning/logistic_regression.py b/machine_learning/logistic_regression.py index 1c1906e8e6b2..48d88ef61185 100644 --- a/machine_learning/logistic_regression.py +++ b/machine_learning/logistic_regression.py @@ -14,14 +14,12 @@ Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ - import numpy as np -import matplotlib.pyplot as plt +from matplotlib import pyplot as plt +from sklearn import datasets # get_ipython().run_line_magic('matplotlib', 'inline') -from sklearn import datasets - # In[67]: diff --git a/machine_learning/lstm/lstm_prediction.py b/machine_learning/lstm/lstm_prediction.py index fbf802f4d8ee..5452f0443f62 100644 --- a/machine_learning/lstm/lstm_prediction.py +++ b/machine_learning/lstm/lstm_prediction.py @@ -4,14 +4,12 @@ * http://colah.github.io/posts/2015-08-Understanding-LSTMs * https://en.wikipedia.org/wiki/Long_short-term_memory """ - -from keras.layers import Dense, LSTM -from keras.models import Sequential import numpy as np import pandas as pd +from keras.layers import LSTM, Dense +from keras.models import Sequential from sklearn.preprocessing import MinMaxScaler - if __name__ == "__main__": """ First part of building a model is to get the data and prepare diff --git a/machine_learning/multilayer_perceptron_classifier.py b/machine_learning/multilayer_perceptron_classifier.py index d78d2a9ed8eb..604185cef677 100644 --- a/machine_learning/multilayer_perceptron_classifier.py +++ b/machine_learning/multilayer_perceptron_classifier.py @@ -1,6 +1,5 @@ from sklearn.neural_network import MLPClassifier - X = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0]] y = [0, 1, 0, 0] diff --git a/machine_learning/polymonial_regression.py b/machine_learning/polymonial_regression.py index f781141f169c..374c35f7f905 100644 --- a/machine_learning/polymonial_regression.py +++ b/machine_learning/polymonial_regression.py @@ -1,5 +1,5 @@ -import matplotlib.pyplot as plt import pandas as pd +from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set diff --git a/machine_learning/random_forest_classifier.py b/machine_learning/random_forest_classifier.py index e7acd91346a1..6370254090f7 100644 --- a/machine_learning/random_forest_classifier.py +++ b/machine_learning/random_forest_classifier.py @@ -1,10 +1,9 @@ # Random Forest Classifier Example - +from matplotlib import pyplot as plt from sklearn.datasets import load_iris -from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import plot_confusion_matrix -import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split def main(): diff --git a/machine_learning/random_forest_regressor.py b/machine_learning/random_forest_regressor.py index f78b6bbd0f42..0aade626b038 100644 --- a/machine_learning/random_forest_regressor.py +++ b/machine_learning/random_forest_regressor.py @@ -1,10 +1,8 @@ # Random Forest Regressor Example - from sklearn.datasets import load_boston -from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor -from sklearn.metrics import mean_absolute_error -from sklearn.metrics import mean_squared_error +from sklearn.metrics import mean_absolute_error, mean_squared_error +from sklearn.model_selection import train_test_split def main(): diff --git a/machine_learning/sequential_minimum_optimization.py b/machine_learning/sequential_minimum_optimization.py index 3583b18ab2e6..98ce05c46cff 100644 --- a/machine_learning/sequential_minimum_optimization.py +++ b/machine_learning/sequential_minimum_optimization.py @@ -36,9 +36,9 @@ import sys import urllib.request -import matplotlib.pyplot as plt import numpy as np import pandas as pd +from matplotlib import pyplot as plt from sklearn.datasets import make_blobs, make_circles from sklearn.preprocessing import StandardScaler diff --git a/machine_learning/support_vector_machines.py b/machine_learning/support_vector_machines.py index 3bf54a69128d..c5e5085d8748 100644 --- a/machine_learning/support_vector_machines.py +++ b/machine_learning/support_vector_machines.py @@ -1,5 +1,5 @@ -from sklearn.datasets import load_iris from sklearn import svm +from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split diff --git a/maths/3n_plus_1.py b/maths/3n_plus_1.py index d3684561827f..baaa74f89bf5 100644 --- a/maths/3n_plus_1.py +++ b/maths/3n_plus_1.py @@ -1,4 +1,4 @@ -from typing import Tuple, List +from typing import List, Tuple def n31(a: int) -> Tuple[List[int], int]: diff --git a/maths/fibonacci.py b/maths/fibonacci.py index d1e8cf7775fd..e6519035401e 100644 --- a/maths/fibonacci.py +++ b/maths/fibonacci.py @@ -7,10 +7,10 @@ reference-->Su, Francis E., et al. "Fibonacci Number Formula." Math Fun Facts. """ -import math import functools +import math import time -from decimal import getcontext, Decimal +from decimal import Decimal, getcontext getcontext().prec = 100 diff --git a/maths/gamma.py b/maths/gamma.py index 9193929baa28..69cd819ef186 100644 --- a/maths/gamma.py +++ b/maths/gamma.py @@ -1,6 +1,7 @@ import math -from scipy.integrate import quad + from numpy import inf +from scipy.integrate import quad def gamma(num: float) -> float: diff --git a/maths/gaussian.py b/maths/gaussian.py index edd52d1a4b2c..5d5800e00989 100644 --- a/maths/gaussian.py +++ b/maths/gaussian.py @@ -5,7 +5,7 @@ python : 3.7.3 """ -from numpy import pi, sqrt, exp +from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int: diff --git a/maths/line_length.py b/maths/line_length.py index 0b1ddb5b7866..6df0a916efe6 100644 --- a/maths/line_length.py +++ b/maths/line_length.py @@ -1,5 +1,5 @@ -from typing import Callable, Union import math as m +from typing import Callable, Union def line_length( diff --git a/maths/mobius_function.py b/maths/mobius_function.py index df0f66177501..4fcf35f21813 100644 --- a/maths/mobius_function.py +++ b/maths/mobius_function.py @@ -5,8 +5,8 @@ flake8 : True """ -from maths.prime_factors import prime_factors from maths.is_square_free import is_square_free +from maths.prime_factors import prime_factors def mobius(n: int) -> int: diff --git a/maths/newton_raphson.py b/maths/newton_raphson.py index 7b16d2dd9b2e..d8a98dfa6703 100644 --- a/maths/newton_raphson.py +++ b/maths/newton_raphson.py @@ -7,7 +7,6 @@ limit is reached or the gradient f'(x[n]) approaches zero. In both cases, exception is raised. If iteration limit is reached, try increasing maxiter. """ - import math as m @@ -42,7 +41,7 @@ def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=Fa if __name__ == "__main__": - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt f = lambda x: m.tanh(x) ** 2 - m.exp(3 * x) # noqa: E731 solution, error, steps = newton_raphson( diff --git a/maths/prime_numbers.py b/maths/prime_numbers.py index 1b2a29f1a203..38bebddeee41 100644 --- a/maths/prime_numbers.py +++ b/maths/prime_numbers.py @@ -1,5 +1,5 @@ -from typing import Generator import math +from typing import Generator def slow_primes(max: int) -> Generator[int, None, None]: diff --git a/maths/relu.py b/maths/relu.py index 38a937decb0c..89667ab3e73f 100644 --- a/maths/relu.py +++ b/maths/relu.py @@ -9,9 +9,9 @@ Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Rectifier_(neural_networks) """ +from typing import List import numpy as np -from typing import List def relu(vector: List[float]): diff --git a/maths/volume.py b/maths/volume.py index 04283743d71f..41d2331db3cb 100644 --- a/maths/volume.py +++ b/maths/volume.py @@ -3,8 +3,8 @@ Wikipedia reference: https://en.wikipedia.org/wiki/Volume """ -from typing import Union from math import pi, pow +from typing import Union def vol_cube(side_length: Union[int, float]) -> float: diff --git a/maths/zellers_congruence.py b/maths/zellers_congruence.py index 9c13c29210b1..8608b32f3ee3 100644 --- a/maths/zellers_congruence.py +++ b/maths/zellers_congruence.py @@ -1,5 +1,5 @@ -import datetime import argparse +import datetime def zeller(date_input: str) -> str: diff --git a/matrix/tests/test_matrix_operation.py b/matrix/tests/test_matrix_operation.py index bf049b32116e..3500dfeb0641 100644 --- a/matrix/tests/test_matrix_operation.py +++ b/matrix/tests/test_matrix_operation.py @@ -6,11 +6,13 @@ -vv -m mat_ops -p no:cacheprovider """ +import logging + # standard libraries import sys + import numpy as np import pytest -import logging # Custom/local libraries from matrix import matrix_operation as matop diff --git a/neural_network/back_propagation_neural_network.py b/neural_network/back_propagation_neural_network.py index c771dc46afc2..43e796e77be3 100644 --- a/neural_network/back_propagation_neural_network.py +++ b/neural_network/back_propagation_neural_network.py @@ -17,9 +17,8 @@ Date: 2017.11.23 """ - import numpy as np -import matplotlib.pyplot as plt +from matplotlib import pyplot as plt def sigmoid(x): diff --git a/neural_network/convolution_neural_network.py b/neural_network/convolution_neural_network.py index ac0eddeb5cb6..d821488025ef 100644 --- a/neural_network/convolution_neural_network.py +++ b/neural_network/convolution_neural_network.py @@ -14,8 +14,9 @@ - - - - - -- - - - - - - - - - - - - - - - - - - - - - - """ import pickle + import numpy as np -import matplotlib.pyplot as plt +from matplotlib import pyplot as plt class CNN: diff --git a/other/least_recently_used.py b/other/least_recently_used.py index e1b5ab5bd380..1b901d544b8d 100644 --- a/other/least_recently_used.py +++ b/other/least_recently_used.py @@ -1,5 +1,5 @@ -from abc import abstractmethod import sys +from abc import abstractmethod from collections import deque diff --git a/other/sierpinski_triangle.py b/other/sierpinski_triangle.py index e27db3a2e8c4..cf41ffa5f190 100644 --- a/other/sierpinski_triangle.py +++ b/other/sierpinski_triangle.py @@ -27,8 +27,8 @@ http://www.riannetrujillo.com/blog/python-fractal/ """ -import turtle import sys +import turtle PROGNAME = "Sierpinski Triangle" diff --git a/project_euler/problem_07/sol3.py b/project_euler/problem_07/sol3.py index 9b02ea87ec49..602eb13b623d 100644 --- a/project_euler/problem_07/sol3.py +++ b/project_euler/problem_07/sol3.py @@ -5,8 +5,8 @@ We can see that the 6th prime is 13. What is the Nth prime number? """ -import math import itertools +import math def primeCheck(number): diff --git a/project_euler/problem_42/solution42.py b/project_euler/problem_42/solution42.py index 2380472153c6..1e9bb49c7a06 100644 --- a/project_euler/problem_42/solution42.py +++ b/project_euler/problem_42/solution42.py @@ -15,7 +15,6 @@ """ import os - # Precomputes a list of the 100 first triangular numbers TRIANGULAR_NUMBERS = [int(0.5 * n * (n + 1)) for n in range(1, 101)] diff --git a/scheduling/shortest_job_first.py b/scheduling/shortest_job_first.py index 8aa642a8b25b..6a2fdeeecc5a 100644 --- a/scheduling/shortest_job_first.py +++ b/scheduling/shortest_job_first.py @@ -3,9 +3,9 @@ Please note arrival time and burst Please use spaces to separate times entered. """ +from typing import List import pandas as pd -from typing import List def calculate_waitingtime( diff --git a/scripts/validate_filenames.py b/scripts/validate_filenames.py index f22fda4149f3..01712e8f7707 100755 --- a/scripts/validate_filenames.py +++ b/scripts/validate_filenames.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 - import os + from build_directory_md import good_file_paths filepaths = list(good_file_paths()) diff --git a/searches/hill_climbing.py b/searches/hill_climbing.py index 324097ef5a24..70622ebefb4e 100644 --- a/searches/hill_climbing.py +++ b/searches/hill_climbing.py @@ -150,7 +150,7 @@ def hill_climbing( solution_found = True if visualization: - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt plt.plot(range(iterations), scores) plt.xlabel("Iterations") diff --git a/searches/simulated_annealing.py b/searches/simulated_annealing.py index b12303274b14..8535e5419a4a 100644 --- a/searches/simulated_annealing.py +++ b/searches/simulated_annealing.py @@ -84,7 +84,7 @@ def simulated_annealing( current_state = next_state if visualization: - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt plt.plot(range(iterations), scores) plt.xlabel("Iterations") diff --git a/searches/tabu_search.py b/searches/tabu_search.py index f0c3241dbe19..24d0dbf6f1c2 100644 --- a/searches/tabu_search.py +++ b/searches/tabu_search.py @@ -24,9 +24,8 @@ -s size_of_tabu_search e.g. python tabu_search.py -f tabudata2.txt -i 4 -s 3 """ - -import copy import argparse +import copy def generate_neighbours(path): diff --git a/sorts/external_sort.py b/sorts/external_sort.py index e5b2c045fa95..060e67adf827 100644 --- a/sorts/external_sort.py +++ b/sorts/external_sort.py @@ -3,8 +3,8 @@ # # Sort large text files in a minimum amount of memory # -import os import argparse +import os class FileSplitter: diff --git a/sorts/random_normal_distribution_quicksort.py b/sorts/random_normal_distribution_quicksort.py index 5da9337ee080..73eb70bea07f 100644 --- a/sorts/random_normal_distribution_quicksort.py +++ b/sorts/random_normal_distribution_quicksort.py @@ -1,5 +1,6 @@ from random import randint from tempfile import TemporaryFile + import numpy as np diff --git a/web_programming/crawl_google_results.py b/web_programming/crawl_google_results.py index 7d2be7c03c22..a33a3f3bbe5c 100644 --- a/web_programming/crawl_google_results.py +++ b/web_programming/crawl_google_results.py @@ -1,10 +1,9 @@ import sys import webbrowser +import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent -import requests - if __name__ == "__main__": print("Googling.....") diff --git a/web_programming/get_imdbtop.py b/web_programming/get_imdbtop.py index 522e423b4eab..669e7f89824b 100644 --- a/web_programming/get_imdbtop.py +++ b/web_programming/get_imdbtop.py @@ -1,5 +1,5 @@ -from bs4 import BeautifulSoup import requests +from bs4 import BeautifulSoup def imdb_top(imdb_top_n):