diff --git a/backtracking/all_combinations.py b/backtracking/all_combinations.py index 60e9579f2..854dc5198 100644 --- a/backtracking/all_combinations.py +++ b/backtracking/all_combinations.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ In this problem, we want to determine all possible combinations of k numbers out of 1 ... n. We use backtracking to solve this problem. diff --git a/ciphers/brute_force_caesar_cipher.py b/ciphers/brute_force_caesar_cipher.py index 2586803ba..5f11cb848 100644 --- a/ciphers/brute_force_caesar_cipher.py +++ b/ciphers/brute_force_caesar_cipher.py @@ -40,7 +40,7 @@ def decrypt(message): translated = translated + LETTERS[num] else: translated = translated + symbol - print("Decryption using Key #%s: %s" % (key, translated)) + print(f"Decryption using Key #{key}: {translated}") def main(): diff --git a/ciphers/hill_cipher.py b/ciphers/hill_cipher.py index e01b6a3f4..05f716f85 100644 --- a/ciphers/hill_cipher.py +++ b/ciphers/hill_cipher.py @@ -78,7 +78,7 @@ class HillCipher: req_l = len(self.key_string) if gcd(det, len(self.key_string)) != 1: raise ValueError( - "discriminant modular {0} of encryption key({1}) is not co prime w.r.t {2}.\nTry another key.".format( + "discriminant modular {} of encryption key({}) is not co prime w.r.t {}.\nTry another key.".format( req_l, det, req_l ) ) diff --git a/ciphers/rsa_cipher.py b/ciphers/rsa_cipher.py index a9b2dcc55..da3778ae9 100644 --- a/ciphers/rsa_cipher.py +++ b/ciphers/rsa_cipher.py @@ -101,7 +101,7 @@ def encryptAndWriteToFile( for i in range(len(encryptedBlocks)): encryptedBlocks[i] = str(encryptedBlocks[i]) encryptedContent = ",".join(encryptedBlocks) - encryptedContent = "%s_%s_%s" % (len(message), blockSize, encryptedContent) + encryptedContent = "{}_{}_{}".format(len(message), blockSize, encryptedContent) with open(messageFilename, "w") as fo: fo.write(encryptedContent) return encryptedContent diff --git a/ciphers/rsa_key_generator.py b/ciphers/rsa_key_generator.py index ce7c1f3dd..729d31c08 100644 --- a/ciphers/rsa_key_generator.py +++ b/ciphers/rsa_key_generator.py @@ -43,11 +43,11 @@ def makeKeyFiles(name, keySize): publicKey, privateKey = generateKey(keySize) print("\nWriting public key to file %s_pubkey.txt..." % name) with open("%s_pubkey.txt" % name, "w") as fo: - fo.write("%s,%s,%s" % (keySize, publicKey[0], publicKey[1])) + fo.write("{},{},{}".format(keySize, publicKey[0], publicKey[1])) print("Writing private key to file %s_privkey.txt..." % name) with open("%s_privkey.txt" % name, "w") as fo: - fo.write("%s,%s,%s" % (keySize, privateKey[0], privateKey[1])) + fo.write("{},{},{}".format(keySize, privateKey[0], privateKey[1])) if __name__ == "__main__": diff --git a/ciphers/shuffled_shift_cipher.py b/ciphers/shuffled_shift_cipher.py index bbefe3305..be5c6caf8 100644 --- a/ciphers/shuffled_shift_cipher.py +++ b/ciphers/shuffled_shift_cipher.py @@ -2,7 +2,7 @@ import random import string -class ShuffledShiftCipher(object): +class ShuffledShiftCipher: """ This algorithm uses the Caesar Cipher algorithm but removes the option to use brute force to decrypt the message. diff --git a/ciphers/simple_substitution_cipher.py b/ciphers/simple_substitution_cipher.py index 12511cc39..7da18482d 100644 --- a/ciphers/simple_substitution_cipher.py +++ b/ciphers/simple_substitution_cipher.py @@ -17,7 +17,7 @@ def main(): mode = "decrypt" translated = decryptMessage(key, message) - print("\n%sion: \n%s" % (mode.title(), translated)) + print("\n{}ion: \n{}".format(mode.title(), translated)) def checkValidKey(key): diff --git a/ciphers/xor_cipher.py b/ciphers/xor_cipher.py index 17e45413a..58b535267 100644 --- a/ciphers/xor_cipher.py +++ b/ciphers/xor_cipher.py @@ -18,7 +18,7 @@ """ -class XORCipher(object): +class XORCipher: def __init__(self, key=0): """ simple constructor that receives a key or uses diff --git a/compression/burrows_wheeler.py b/compression/burrows_wheeler.py index 50ee62aa0..1c7939b39 100644 --- a/compression/burrows_wheeler.py +++ b/compression/burrows_wheeler.py @@ -135,16 +135,14 @@ def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( - ( - "The parameter idx_original_string type must be int or passive" - " of cast to int." - ) + "The parameter idx_original_string type must be int or passive" + " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( - ("The parameter idx_original_string must be lower than" " len(bwt_string).") + "The parameter idx_original_string must be lower than" " len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) diff --git a/data_structures/binary_tree/avl_tree.py b/data_structures/binary_tree/avl_tree.py index 31d12c811..2df747c10 100644 --- a/data_structures/binary_tree/avl_tree.py +++ b/data_structures/binary_tree/avl_tree.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ An auto-balanced binary tree! """ diff --git a/data_structures/binary_tree/red_black_tree.py b/data_structures/binary_tree/red_black_tree.py index 908f13cd5..088476650 100644 --- a/data_structures/binary_tree/red_black_tree.py +++ b/data_structures/binary_tree/red_black_tree.py @@ -467,7 +467,7 @@ class RedBlackTree: from pprint import pformat if self.left is None and self.right is None: - return "'%s %s'" % (self.label, (self.color and "red") or "blk") + return "'{} {}'".format(self.label, (self.color and "red") or "blk") return pformat( { "%s %s" diff --git a/data_structures/binary_tree/treap.py b/data_structures/binary_tree/treap.py index 6bc2403f7..d2e3fb88e 100644 --- a/data_structures/binary_tree/treap.py +++ b/data_structures/binary_tree/treap.py @@ -2,7 +2,7 @@ from random import random from typing import Tuple -class Node(object): +class Node: """ Treap's node Treap is a binary tree by value and heap by priority @@ -18,11 +18,10 @@ class Node(object): from pprint import pformat if self.left is None and self.right is None: - return "'%s: %.5s'" % (self.value, self.prior) + return f"'{self.value}: {self.prior:.5}'" else: return pformat( - {"%s: %.5s" % (self.value, self.prior): (self.left, self.right)}, - indent=1, + {f"{self.value}: {self.prior:.5}": (self.left, self.right)}, indent=1, ) def __str__(self): diff --git a/data_structures/data_structures/heap/heap_generic.py b/data_structures/data_structures/heap/heap_generic.py index fc17c1b12..8993d5013 100644 --- a/data_structures/data_structures/heap/heap_generic.py +++ b/data_structures/data_structures/heap/heap_generic.py @@ -1,4 +1,4 @@ -class Heap(object): +class Heap: """A generic Heap class, can be used as min or max by passing the key function accordingly. """ diff --git a/data_structures/hashing/hash_table.py b/data_structures/hashing/hash_table.py index ab473dc52..69eaa65d8 100644 --- a/data_structures/hashing/hash_table.py +++ b/data_structures/hashing/hash_table.py @@ -28,7 +28,7 @@ class HashTable: def _step_by_step(self, step_ord): - print("step {0}".format(step_ord)) + print(f"step {step_ord}") print([i for i in range(len(self.values))]) print(self.values) diff --git a/data_structures/stacks/stack.py b/data_structures/stacks/stack.py index 9f5b27971..53a40a7b7 100644 --- a/data_structures/stacks/stack.py +++ b/data_structures/stacks/stack.py @@ -1,7 +1,7 @@ __author__ = "Omkar Pathak" -class Stack(object): +class Stack: """ A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top diff --git a/digital_image_processing/histogram_equalization/histogram_stretch.py b/digital_image_processing/histogram_equalization/histogram_stretch.py index b6557d6ef..d4a6c0841 100644 --- a/digital_image_processing/histogram_equalization/histogram_stretch.py +++ b/digital_image_processing/histogram_equalization/histogram_stretch.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Created on Fri Sep 28 15:22:29 2018 diff --git a/digital_image_processing/index_calculation.py b/digital_image_processing/index_calculation.py index fc5b16965..0786314e1 100644 --- a/digital_image_processing/index_calculation.py +++ b/digital_image_processing/index_calculation.py @@ -389,10 +389,7 @@ class IndexCalculation: :return: index """ return np.arctan( - ( - ((2 * self.red - self.green - self.blue) / 30.5) - * (self.green - self.blue) - ) + ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def IVI(self, a=None, b=None): diff --git a/dynamic_programming/fast_fibonacci.py b/dynamic_programming/fast_fibonacci.py index 47248078b..77094a403 100644 --- a/dynamic_programming/fast_fibonacci.py +++ b/dynamic_programming/fast_fibonacci.py @@ -1,5 +1,4 @@ #!/usr/bin/python -# encoding=utf8 """ This program calculates the nth Fibonacci number in O(log(n)). diff --git a/dynamic_programming/k_means_clustering_tensorflow.py b/dynamic_programming/k_means_clustering_tensorflow.py index 6b1eb628e..4fbcedeaa 100644 --- a/dynamic_programming/k_means_clustering_tensorflow.py +++ b/dynamic_programming/k_means_clustering_tensorflow.py @@ -40,7 +40,7 @@ def TFKMeansCluster(vectors, noofclusters): ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points centroids = [ - tf.Variable((vectors[vector_indices[i]])) for i in range(noofclusters) + tf.Variable(vectors[vector_indices[i]]) for i in range(noofclusters) ] ##These nodes will assign the centroid Variables the appropriate ##values diff --git a/dynamic_programming/matrix_chain_order.py b/dynamic_programming/matrix_chain_order.py index f88a9be8a..9411bc704 100644 --- a/dynamic_programming/matrix_chain_order.py +++ b/dynamic_programming/matrix_chain_order.py @@ -46,7 +46,7 @@ def main(): # 30*35 35*15 15*5 5*10 10*20 20*25 Matrix, OptimalSolution = MatrixChainOrder(array) - print("No. of Operation required: " + str((Matrix[1][n - 1]))) + print("No. of Operation required: " + str(Matrix[1][n - 1])) PrintOptimalSolution(OptimalSolution, 1, n - 1) diff --git a/graphs/basic_graphs.py b/graphs/basic_graphs.py index 161bc0c09..070af5f55 100644 --- a/graphs/basic_graphs.py +++ b/graphs/basic_graphs.py @@ -48,7 +48,7 @@ if __name__ == "__main__": def dfs(G, s): - vis, S = set([s]), [s] + vis, S = {s}, [s] print(s) while S: flag = 0 @@ -76,7 +76,7 @@ from collections import deque def bfs(G, s): - vis, Q = set([s]), deque([s]) + vis, Q = {s}, deque([s]) print(s) while Q: u = Q.popleft() @@ -255,7 +255,7 @@ def krusk(E_and_n): # Sort edges on the basis of distance (E, n) = E_and_n E.sort(reverse=True, key=lambda x: x[2]) - s = [set([i]) for i in range(1, n + 1)] + s = [{i} for i in range(1, n + 1)] while True: if len(s) == 1: break diff --git a/graphs/breadth_first_search.py b/graphs/breadth_first_search.py index 8516e60a5..faa166150 100644 --- a/graphs/breadth_first_search.py +++ b/graphs/breadth_first_search.py @@ -1,5 +1,4 @@ #!/usr/bin/python -# encoding=utf8 """ Author: OMKAR PATHAK """ diff --git a/graphs/depth_first_search.py b/graphs/depth_first_search.py index 5347c2fbc..2fe9dd157 100644 --- a/graphs/depth_first_search.py +++ b/graphs/depth_first_search.py @@ -1,5 +1,4 @@ #!/usr/bin/python -# encoding=utf8 """ Author: OMKAR PATHAK """ diff --git a/graphs/edmonds_karp_multiple_source_and_sink.py b/graphs/edmonds_karp_multiple_source_and_sink.py index eb6ec739b..0f359ff1a 100644 --- a/graphs/edmonds_karp_multiple_source_and_sink.py +++ b/graphs/edmonds_karp_multiple_source_and_sink.py @@ -57,7 +57,7 @@ class FlowNetwork: self.maximumFlowAlgorithm = Algorithm(self) -class FlowNetworkAlgorithmExecutor(object): +class FlowNetworkAlgorithmExecutor: def __init__(self, flowNetwork): self.flowNetwork = flowNetwork self.verticesCount = flowNetwork.verticesCount @@ -80,7 +80,7 @@ class FlowNetworkAlgorithmExecutor(object): class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor): def __init__(self, flowNetwork): - super(MaximumFlowAlgorithmExecutor, self).__init__(flowNetwork) + super().__init__(flowNetwork) # use this to save your result self.maximumFlow = -1 @@ -93,7 +93,7 @@ class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor): class PushRelabelExecutor(MaximumFlowAlgorithmExecutor): def __init__(self, flowNetwork): - super(PushRelabelExecutor, self).__init__(flowNetwork) + super().__init__(flowNetwork) self.preflow = [[0] * self.verticesCount for i in range(self.verticesCount)] diff --git a/graphs/graph_list.py b/graphs/graph_list.py index 4f0cbf15c..a20940ab1 100644 --- a/graphs/graph_list.py +++ b/graphs/graph_list.py @@ -1,12 +1,11 @@ #!/usr/bin/python -# encoding=utf8 # Author: OMKAR PATHAK # We can use Python's dictionary for constructing the graph. -class AdjacencyList(object): +class AdjacencyList: def __init__(self): self.List = {} diff --git a/hashes/hamming_code.py b/hashes/hamming_code.py index 155c1b10a..3e0424490 100644 --- a/hashes/hamming_code.py +++ b/hashes/hamming_code.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Author: João Gustavo A. Amorim & Gabriel Kunz # Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br # Coding date: apr 2019 @@ -100,7 +99,7 @@ def emitterConverter(sizePar, data): # Performs a template of bit positions - who should be given, # and who should be parity if qtdBP < sizePar: - if ((np.log(x) / np.log(2))).is_integer(): + if (np.log(x) / np.log(2)).is_integer(): dataOutGab.append("P") qtdBP = qtdBP + 1 else: @@ -170,7 +169,7 @@ def receptorConverter(sizePar, data): # Performs a template of bit positions - who should be given, # and who should be parity if qtdBP < sizePar: - if ((np.log(x) / np.log(2))).is_integer(): + if (np.log(x) / np.log(2)).is_integer(): dataOutGab.append("P") qtdBP = qtdBP + 1 else: @@ -204,7 +203,7 @@ def receptorConverter(sizePar, data): # Performs a template position of bits - who should be given, # and who should be parity if qtdBP < sizePar: - if ((np.log(x) / np.log(2))).is_integer(): + if (np.log(x) / np.log(2)).is_integer(): dataOutGab.append("P") qtdBP = qtdBP + 1 else: diff --git a/linear_algebra/src/lib.py b/linear_algebra/src/lib.py index 15d176cc6..f4628f1d9 100644 --- a/linear_algebra/src/lib.py +++ b/linear_algebra/src/lib.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Created on Mon Feb 26 14:29:11 2018 @@ -25,7 +24,7 @@ import math import random -class Vector(object): +class Vector: """ This class represents a vector of arbitrary size. You need to give the vector components. @@ -205,7 +204,7 @@ def randomVector(N, a, b): return Vector(ans) -class Matrix(object): +class Matrix: """ class: Matrix This class represents a arbitrary matrix. diff --git a/linear_algebra/src/test_linear_algebra.py b/linear_algebra/src/test_linear_algebra.py index f8e7db7de..5e28910af 100644 --- a/linear_algebra/src/test_linear_algebra.py +++ b/linear_algebra/src/test_linear_algebra.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Created on Mon Feb 26 15:40:07 2018 diff --git a/machine_learning/k_means_clust.py b/machine_learning/k_means_clust.py index 4c643226b..7a4f69eb7 100644 --- a/machine_learning/k_means_clust.py +++ b/machine_learning/k_means_clust.py @@ -126,7 +126,7 @@ def plot_heterogeneity(heterogeneity, k): plt.plot(heterogeneity, linewidth=4) plt.xlabel("# Iterations") plt.ylabel("Heterogeneity") - plt.title("Heterogeneity of clustering over time, K={0:d}".format(k)) + plt.title(f"Heterogeneity of clustering over time, K={k:d}") plt.rcParams.update({"font.size": 16}) plt.show() @@ -164,7 +164,7 @@ def kmeans( num_changed = np.sum(prev_cluster_assignment != cluster_assignment) if verbose: print( - " {0:5d} elements changed their cluster assignment.".format( + " {:5d} elements changed their cluster assignment.".format( num_changed ) ) diff --git a/machine_learning/logistic_regression.py b/machine_learning/logistic_regression.py index f23d400ce..f5edfb9c5 100644 --- a/machine_learning/logistic_regression.py +++ b/machine_learning/logistic_regression.py @@ -1,5 +1,4 @@ #!/usr/bin/python -# -*- coding: utf-8 -*- ## Logistic Regression from scratch diff --git a/machine_learning/sequential_minimum_optimization.py b/machine_learning/sequential_minimum_optimization.py index aa997d88c..0612392c8 100644 --- a/machine_learning/sequential_minimum_optimization.py +++ b/machine_learning/sequential_minimum_optimization.py @@ -1,4 +1,3 @@ -# coding: utf-8 """ Implementation of sequential minimal optimization(SMO) for support vector machines(SVM). @@ -29,7 +28,6 @@ Reference: http://web.cs.iastate.edu/~honavar/smo-svm.pdf """ -from __future__ import division import os import sys @@ -44,7 +42,7 @@ from sklearn.preprocessing import StandardScaler CANCER_DATASET_URL = "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data" -class SmoSVM(object): +class SmoSVM: def __init__( self, train, @@ -405,7 +403,7 @@ class SmoSVM(object): return self.samples.shape[0] -class Kernel(object): +class Kernel: def __init__(self, kernel, degree=1.0, coef0=0.0, gamma=1.0): self.degree = np.float64(degree) self.coef0 = np.float64(coef0) diff --git a/maths/3n+1.py b/maths/3n+1.py index f6fe77b2b..64ff34fd2 100644 --- a/maths/3n+1.py +++ b/maths/3n+1.py @@ -9,9 +9,9 @@ def n31(a: int) -> Tuple[List[int], int]: """ if not isinstance(a, int): - raise TypeError("Must be int, not {0}".format(type(a).__name__)) + raise TypeError("Must be int, not {}".format(type(a).__name__)) if a < 1: - raise ValueError("Given integer must be greater than 1, not {0}".format(a)) + raise ValueError(f"Given integer must be greater than 1, not {a}") path = [a] while a != 1: diff --git a/maths/__init__.py b/maths/__init__.py index 8b1378917..e69de29bb 100644 --- a/maths/__init__.py +++ b/maths/__init__.py @@ -1 +0,0 @@ - diff --git a/maths/hardy_ramanujanalgo.py b/maths/hardy_ramanujanalgo.py index bb31a1be4..90e4913c7 100644 --- a/maths/hardy_ramanujanalgo.py +++ b/maths/hardy_ramanujanalgo.py @@ -37,7 +37,7 @@ def exactPrimeFactorCount(n): if __name__ == "__main__": n = 51242183 print(f"The number of distinct prime factors is/are {exactPrimeFactorCount(n)}") - print("The value of log(log(n)) is {0:.4f}".format(math.log(math.log(n)))) + print("The value of log(log(n)) is {:.4f}".format(math.log(math.log(n)))) """ The number of distinct prime factors is/are 3 diff --git a/maths/lucas_lehmer_primality_test.py b/maths/lucas_lehmer_primality_test.py index 44e41ba58..8dac658f1 100644 --- a/maths/lucas_lehmer_primality_test.py +++ b/maths/lucas_lehmer_primality_test.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ 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 diff --git a/maths/matrix_exponentiation.py b/maths/matrix_exponentiation.py index c20292735..a8f114803 100644 --- a/maths/matrix_exponentiation.py +++ b/maths/matrix_exponentiation.py @@ -10,7 +10,7 @@ https://www.hackerearth.com/practice/notes/matrix-exponentiation-1/ """ -class Matrix(object): +class Matrix: def __init__(self, arg): if isinstance(arg, list): # Initialzes a matrix identical to the one provided. self.t = arg diff --git a/maths/newton_raphson.py b/maths/newton_raphson.py index 093cc4438..c4975c73e 100644 --- a/maths/newton_raphson.py +++ b/maths/newton_raphson.py @@ -52,4 +52,4 @@ if __name__ == "__main__": plt.xlabel("step") plt.ylabel("error") plt.show() - print("solution = {%f}, error = {%f}" % (solution, error)) + print(f"solution = {{{solution:f}}}, error = {{{error:f}}}") diff --git a/maths/pythagoras.py b/maths/pythagoras.py index 2f59107cd..69a17731a 100644 --- a/maths/pythagoras.py +++ b/maths/pythagoras.py @@ -14,7 +14,7 @@ class Point: def distance(a: Point, b: Point) -> float: - return math.sqrt(abs(((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2))) + return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: diff --git a/maths/sieve_of_eratosthenes.py b/maths/sieve_of_eratosthenes.py index 44c7f8a02..4761c9339 100644 --- a/maths/sieve_of_eratosthenes.py +++ b/maths/sieve_of_eratosthenes.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Sieve of Eratosthones diff --git a/matrix/matrix_operation.py b/matrix/matrix_operation.py index 5ca61b4ed..26e21aafc 100644 --- a/matrix/matrix_operation.py +++ b/matrix/matrix_operation.py @@ -148,9 +148,9 @@ def main(): % (matrix_a, matrix_b, multiply(matrix_a, matrix_b)) ) print("Identity: %s \n" % identity(5)) - print("Minor of %s = %s \n" % (matrix_c, minor(matrix_c, 1, 2))) - print("Determinant of %s = %s \n" % (matrix_b, determinant(matrix_b))) - print("Inverse of %s = %s\n" % (matrix_d, inverse(matrix_d))) + print("Minor of {} = {} \n".format(matrix_c, minor(matrix_c, 1, 2))) + print("Determinant of {} = {} \n".format(matrix_b, determinant(matrix_b))) + print("Inverse of {} = {}\n".format(matrix_d, inverse(matrix_d))) if __name__ == "__main__": diff --git a/matrix/rotate_matrix.py b/matrix/rotate_matrix.py index 822851826..14a9493cd 100644 --- a/matrix/rotate_matrix.py +++ b/matrix/rotate_matrix.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ In this problem, we want to rotate the matrix elements by 90, 180, 270 (counterclockwise) Discussion in stackoverflow: diff --git a/matrix/searching_in_sorted_matrix.py b/matrix/searching_in_sorted_matrix.py index 1b3eeedf3..3897ffb1d 100644 --- a/matrix/searching_in_sorted_matrix.py +++ b/matrix/searching_in_sorted_matrix.py @@ -2,7 +2,7 @@ def search_in_a_sorted_matrix(mat, m, n, key): i, j = m - 1, 0 while i >= 0 and j < n: if key == mat[i][j]: - print("Key %s found at row- %s column- %s" % (key, i + 1, j + 1)) + print("Key {} found at row- {} column- {}".format(key, i + 1, j + 1)) return if key < mat[i][j]: i -= 1 diff --git a/matrix/sherman_morrison.py b/matrix/sherman_morrison.py index 531b76cde..257cf3371 100644 --- a/matrix/sherman_morrison.py +++ b/matrix/sherman_morrison.py @@ -176,7 +176,7 @@ class Matrix: return result else: raise TypeError( - "Unsupported type given for another (%s)" % (type(another),) + "Unsupported type given for another ({})".format(type(another)) ) def transpose(self): @@ -248,17 +248,17 @@ if __name__ == "__main__": ainv = Matrix(3, 3, 0) for i in range(3): ainv[i, i] = 1 - print("a^(-1) is %s" % (ainv,)) + print(f"a^(-1) is {ainv}") # u, v u = Matrix(3, 1, 0) u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 - print("u is %s" % (u,)) - print("v is %s" % (v,)) + print(f"u is {u}") + print(f"v is {v}") print("uv^T is %s" % (u * v.transpose())) # Sherman Morrison - print("(a + uv^T)^(-1) is %s" % (ainv.ShermanMorrison(u, v),)) + print("(a + uv^T)^(-1) is {}".format(ainv.ShermanMorrison(u, v))) def test2(): import doctest diff --git a/neural_network/back_propagation_neural_network.py b/neural_network/back_propagation_neural_network.py index 224fc85de..c771dc46a 100644 --- a/neural_network/back_propagation_neural_network.py +++ b/neural_network/back_propagation_neural_network.py @@ -1,5 +1,4 @@ #!/usr/bin/python -# encoding=utf8 """ @@ -31,6 +30,7 @@ class DenseLayer: """ Layers of BP neural network """ + def __init__( self, units, activation=None, learning_rate=None, is_input_layer=False ): @@ -99,6 +99,7 @@ class BPNN: """ Back Propagation Neural Network model """ + def __init__(self): self.layers = [] self.train_mse = [] diff --git a/neural_network/convolution_neural_network.py b/neural_network/convolution_neural_network.py index 9448671ab..ecc8e3392 100644 --- a/neural_network/convolution_neural_network.py +++ b/neural_network/convolution_neural_network.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ - - - - - -- - - - - - - - - - - - - - - - - - - - - - - Name - - CNN - Convolution Neural Network For Photo Recognizing @@ -286,7 +284,7 @@ class CNN: self.thre_bp3 = self.thre_bp3 - pd_k_all * self.rate_thre self.thre_bp2 = self.thre_bp2 - pd_j_all * self.rate_thre # calculate the sum error of all single image - errors = np.sum(abs((data_teach - bp_out3))) + errors = np.sum(abs(data_teach - bp_out3)) alle = alle + errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) diff --git a/neural_network/input_data.py b/neural_network/input_data.py index ea826be6c..0e22ac0bc 100644 --- a/neural_network/input_data.py +++ b/neural_network/input_data.py @@ -17,9 +17,6 @@ This module and all its submodules are deprecated. """ -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function import collections import gzip @@ -115,7 +112,7 @@ def _extract_labels(f, one_hot=False, num_classes=10): return labels -class _DataSet(object): +class _DataSet: """Container class for a _DataSet (deprecated). THIS CLASS IS DEPRECATED. @@ -165,7 +162,7 @@ class _DataSet(object): else: assert ( images.shape[0] == labels.shape[0] - ), "images.shape: %s labels.shape: %s" % (images.shape, labels.shape) + ), f"images.shape: {images.shape} labels.shape: {labels.shape}" self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] diff --git a/other/anagrams.py b/other/anagrams.py index 9e103296b..6e6806e92 100644 --- a/other/anagrams.py +++ b/other/anagrams.py @@ -4,7 +4,7 @@ start_time = time.time() print("creating word list...") path = os.path.split(os.path.realpath(__file__)) with open(path[0] + "/words") as f: - word_list = sorted(list(set([word.strip().lower() for word in f]))) + word_list = sorted(list({word.strip().lower() for word in f})) def signature(word): diff --git a/other/fischer_yates_shuffle.py b/other/fischer_yates_shuffle.py index 977e5f131..4217cb0be 100644 --- a/other/fischer_yates_shuffle.py +++ b/other/fischer_yates_shuffle.py @@ -1,5 +1,4 @@ #!/usr/bin/python -# encoding=utf8 """ The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite sequence. For more details visit diff --git a/other/linear_congruential_generator.py b/other/linear_congruential_generator.py index 3b150f422..ea0adc7d0 100644 --- a/other/linear_congruential_generator.py +++ b/other/linear_congruential_generator.py @@ -3,7 +3,7 @@ __author__ = "Tobias Carryer" from time import time -class LinearCongruentialGenerator(object): +class LinearCongruentialGenerator: """ A pseudorandom number generator. """ diff --git a/other/primelib.py b/other/primelib.py index 6fc5eddeb..ff438755a 100644 --- a/other/primelib.py +++ b/other/primelib.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Created on Thu Oct 5 16:44:23 2017 diff --git a/other/sierpinski_triangle.py b/other/sierpinski_triangle.py index 0e6ce43e3..a262900a8 100644 --- a/other/sierpinski_triangle.py +++ b/other/sierpinski_triangle.py @@ -1,5 +1,4 @@ #!/usr/bin/python -# encoding=utf8 """Author Anurag Kumar | anuragkumarak95@gmail.com | git/anuragkumarak95 diff --git a/project_euler/problem_06/sol1.py b/project_euler/problem_06/sol1.py index c69b6c89e..513b35467 100644 --- a/project_euler/problem_06/sol1.py +++ b/project_euler/problem_06/sol1.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Problem: diff --git a/project_euler/problem_06/sol2.py b/project_euler/problem_06/sol2.py index 1698a3fb6..18cdb5175 100644 --- a/project_euler/problem_06/sol2.py +++ b/project_euler/problem_06/sol2.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Problem: diff --git a/project_euler/problem_06/sol3.py b/project_euler/problem_06/sol3.py index f9c5dacb3..ee739c9a1 100644 --- a/project_euler/problem_06/sol3.py +++ b/project_euler/problem_06/sol3.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Problem: diff --git a/project_euler/problem_06/sol4.py b/project_euler/problem_06/sol4.py index 1e1de5570..07eed57ba 100644 --- a/project_euler/problem_06/sol4.py +++ b/project_euler/problem_06/sol4.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Problem: diff --git a/project_euler/problem_07/sol1.py b/project_euler/problem_07/sol1.py index d8d67e157..f6b2584d9 100644 --- a/project_euler/problem_07/sol1.py +++ b/project_euler/problem_07/sol1.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ By listing the first six prime numbers: diff --git a/project_euler/problem_07/sol2.py b/project_euler/problem_07/sol2.py index 5d30e540b..6bfc5881f 100644 --- a/project_euler/problem_07/sol2.py +++ b/project_euler/problem_07/sol2.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ By listing the first six prime numbers: diff --git a/project_euler/problem_07/sol3.py b/project_euler/problem_07/sol3.py index 3c28ecf7f..9b02ea87e 100644 --- a/project_euler/problem_07/sol3.py +++ b/project_euler/problem_07/sol3.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ By listing the first six prime numbers: diff --git a/project_euler/problem_08/sol1.py b/project_euler/problem_08/sol1.py index 6752fae3d..e7582d46c 100644 --- a/project_euler/problem_08/sol1.py +++ b/project_euler/problem_08/sol1.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. diff --git a/project_euler/problem_08/sol2.py b/project_euler/problem_08/sol2.py index bae96e373..bf8afa837 100644 --- a/project_euler/problem_08/sol2.py +++ b/project_euler/problem_08/sol2.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. diff --git a/project_euler/problem_08/sol3.py b/project_euler/problem_08/sol3.py index fe9901742..dfbef5755 100644 --- a/project_euler/problem_08/sol3.py +++ b/project_euler/problem_08/sol3.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. diff --git a/project_euler/problem_14/sol1.py b/project_euler/problem_14/sol1.py index ab09937fb..fda45bc94 100644 --- a/project_euler/problem_14/sol1.py +++ b/project_euler/problem_14/sol1.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Problem Statement: The following iterative sequence is defined for the set of positive integers: diff --git a/project_euler/problem_14/sol2.py b/project_euler/problem_14/sol2.py index 9b8857e71..375a34c72 100644 --- a/project_euler/problem_14/sol2.py +++ b/project_euler/problem_14/sol2.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Collatz conjecture: start with any positive integer n. Next term obtained from the previous term as follows: diff --git a/project_euler/problem_21/sol1.py b/project_euler/problem_21/sol1.py index 49c2db964..f01c9d0da 100644 --- a/project_euler/problem_21/sol1.py +++ b/project_euler/problem_21/sol1.py @@ -1,4 +1,3 @@ -# -.- coding: latin-1 -.- from math import sqrt """ diff --git a/project_euler/problem_22/sol1.py b/project_euler/problem_22/sol1.py index f6275e213..982906245 100644 --- a/project_euler/problem_22/sol1.py +++ b/project_euler/problem_22/sol1.py @@ -1,4 +1,3 @@ -# -*- coding: latin-1 -*- """ Name scores Problem 22 diff --git a/project_euler/problem_22/sol2.py b/project_euler/problem_22/sol2.py index 69acd2fb8..5ae41c846 100644 --- a/project_euler/problem_22/sol2.py +++ b/project_euler/problem_22/sol2.py @@ -1,4 +1,3 @@ -# -*- coding: latin-1 -*- """ Name scores Problem 22 diff --git a/project_euler/problem_25/sol1.py b/project_euler/problem_25/sol1.py index 8fce32285..f0228915d 100644 --- a/project_euler/problem_25/sol1.py +++ b/project_euler/problem_25/sol1.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The Fibonacci sequence is defined by the recurrence relation: diff --git a/project_euler/problem_25/sol2.py b/project_euler/problem_25/sol2.py index d754e2ddd..c98f09b1d 100644 --- a/project_euler/problem_25/sol2.py +++ b/project_euler/problem_25/sol2.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The Fibonacci sequence is defined by the recurrence relation: diff --git a/project_euler/problem_25/sol3.py b/project_euler/problem_25/sol3.py index 4e3084ce5..4a1d9da76 100644 --- a/project_euler/problem_25/sol3.py +++ b/project_euler/problem_25/sol3.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The Fibonacci sequence is defined by the recurrence relation: diff --git a/project_euler/problem_31/sol1.py b/project_euler/problem_31/sol1.py index 187fb9167..1c59658b8 100644 --- a/project_euler/problem_31/sol1.py +++ b/project_euler/problem_31/sol1.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Coin sums Problem 31 diff --git a/project_euler/problem_32/sol32.py b/project_euler/problem_32/sol32.py index 0abc04829..393218339 100644 --- a/project_euler/problem_32/sol32.py +++ b/project_euler/problem_32/sol32.py @@ -46,13 +46,11 @@ def solution(): """ return sum( - set( - [ - int("".join(pandigital[5:9])) - for pandigital in itertools.permutations("123456789") - if isCombinationValid(pandigital) - ] - ) + { + int("".join(pandigital[5:9])) + for pandigital in itertools.permutations("123456789") + if isCombinationValid(pandigital) + } ) diff --git a/project_euler/problem_33/__init__.py b/project_euler/problem_33/__init__.py index 8b1378917..e69de29bb 100644 --- a/project_euler/problem_33/__init__.py +++ b/project_euler/problem_33/__init__.py @@ -1 +0,0 @@ - diff --git a/project_euler/problem_33/sol1.py b/project_euler/problem_33/sol1.py index 0992c9693..73a49023a 100644 --- a/project_euler/problem_33/sol1.py +++ b/project_euler/problem_33/sol1.py @@ -43,7 +43,7 @@ def solve(digit_len: int) -> str: while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if isDigitCancelling(num, den): - solutions.append("{}/{}".format(num, den)) + solutions.append(f"{num}/{den}") den += 1 num += 1 den = 10 diff --git a/project_euler/problem_40/sol1.py b/project_euler/problem_40/sol1.py index 786725e27..69be37772 100644 --- a/project_euler/problem_40/sol1.py +++ b/project_euler/problem_40/sol1.py @@ -1,4 +1,3 @@ -# -.- coding: latin-1 -.- """ Champernowne's constant Problem 40 diff --git a/project_euler/problem_53/sol1.py b/project_euler/problem_53/sol1.py index f17508b00..0692bbe0e 100644 --- a/project_euler/problem_53/sol1.py +++ b/project_euler/problem_53/sol1.py @@ -1,4 +1,3 @@ -# -.- coding: latin-1 -.- """ Combinatoric selections Problem 53 diff --git a/sorts/external_sort.py b/sorts/external_sort.py index abdcb29f9..e5b2c045f 100644 --- a/sorts/external_sort.py +++ b/sorts/external_sort.py @@ -7,7 +7,7 @@ import os import argparse -class FileSplitter(object): +class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): @@ -44,7 +44,7 @@ class FileSplitter(object): map(lambda f: os.remove(f), self.block_filenames) -class NWayMerge(object): +class NWayMerge: def select(self, choices): min_index = -1 min_str = None @@ -56,7 +56,7 @@ class NWayMerge(object): return min_index -class FilesArray(object): +class FilesArray: def __init__(self, files): self.files = files self.empty = set() @@ -89,7 +89,7 @@ class FilesArray(object): return value -class FileMerger(object): +class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy @@ -109,7 +109,7 @@ class FileMerger(object): return files -class ExternalSort(object): +class ExternalSort: def __init__(self, block_size): self.block_size = block_size diff --git a/strings/aho-corasick.py b/strings/aho-corasick.py index b2f89450e..d63dc94a0 100644 --- a/strings/aho-corasick.py +++ b/strings/aho-corasick.py @@ -82,7 +82,7 @@ class Automaton: for key in self.adlist[current_state]["output"]: if not (key in result): result[key] = [] - result[key].append((i - len(key) + 1)) + result[key].append(i - len(key) + 1) return result