Skip to content

Commit

Permalink
pyupgrade --py37-plus **/*.py (TheAlgorithms#1654)
Browse files Browse the repository at this point in the history
* pyupgrade --py37-plus **/*.py

* fixup! Format Python code with psf/black push
  • Loading branch information
cclauss authored and poyea committed Jan 3, 2020
1 parent 34c808b commit 28419cf
Show file tree
Hide file tree
Showing 77 changed files with 71 additions and 128 deletions.
2 changes: 0 additions & 2 deletions backtracking/all_combinations.py
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 1 addition & 1 deletion ciphers/brute_force_caesar_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
2 changes: 1 addition & 1 deletion ciphers/hill_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def checkDeterminant(self):
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
)
)
Expand Down
2 changes: 1 addition & 1 deletion ciphers/rsa_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions ciphers/rsa_key_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
2 changes: 1 addition & 1 deletion ciphers/shuffled_shift_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
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.
Expand Down
2 changes: 1 addition & 1 deletion ciphers/simple_substitution_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion ciphers/xor_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"""


class XORCipher(object):
class XORCipher:
def __init__(self, key=0):
"""
simple constructor that receives a key or uses
Expand Down
8 changes: 3 additions & 5 deletions compression/burrows_wheeler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion data_structures/binary_tree/avl_tree.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
An auto-balanced binary tree!
"""
Expand Down
2 changes: 1 addition & 1 deletion data_structures/binary_tree/red_black_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ def __repr__(self):
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"
Expand Down
7 changes: 3 additions & 4 deletions data_structures/binary_tree/treap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import Tuple


class Node(object):
class Node:
"""
Treap's node
Treap is a binary tree by value and heap by priority
Expand All @@ -18,11 +18,10 @@ def __repr__(self):
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):
Expand Down
2 changes: 1 addition & 1 deletion data_structures/data_structures/heap/heap_generic.py
Original file line number Diff line number Diff line change
@@ -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.
"""

Expand Down
2 changes: 1 addition & 1 deletion data_structures/hashing/hash_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def hash_function(self, key):

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)

Expand Down
2 changes: 1 addition & 1 deletion data_structures/stacks/stack.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 28 15:22:29 2018
Expand Down
5 changes: 1 addition & 4 deletions digital_image_processing/index_calculation.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,10 +389,7 @@ def Hue(self):
: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):
Expand Down
1 change: 0 additions & 1 deletion dynamic_programming/fast_fibonacci.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/python
# encoding=utf8

"""
This program calculates the nth Fibonacci number in O(log(n)).
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/k_means_clustering_tensorflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/matrix_chain_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
6 changes: 3 additions & 3 deletions graphs/basic_graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@


def dfs(G, s):
vis, S = set([s]), [s]
vis, S = {s}, [s]
print(s)
while S:
flag = 0
Expand Down Expand Up @@ -76,7 +76,7 @@ def dfs(G, s):


def bfs(G, s):
vis, Q = set([s]), deque([s])
vis, Q = {s}, deque([s])
print(s)
while Q:
u = Q.popleft()
Expand Down Expand Up @@ -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
Expand Down
1 change: 0 additions & 1 deletion graphs/breadth_first_search.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/python
# encoding=utf8

""" Author: OMKAR PATHAK """

Expand Down
1 change: 0 additions & 1 deletion graphs/depth_first_search.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/python
# encoding=utf8

""" Author: OMKAR PATHAK """

Expand Down
6 changes: 3 additions & 3 deletions graphs/edmonds_karp_multiple_source_and_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def setMaximumFlowAlgorithm(self, Algorithm):
self.maximumFlowAlgorithm = Algorithm(self)


class FlowNetworkAlgorithmExecutor(object):
class FlowNetworkAlgorithmExecutor:
def __init__(self, flowNetwork):
self.flowNetwork = flowNetwork
self.verticesCount = flowNetwork.verticesCount
Expand All @@ -80,7 +80,7 @@ def _algorithm(self):

class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor):
def __init__(self, flowNetwork):
super(MaximumFlowAlgorithmExecutor, self).__init__(flowNetwork)
super().__init__(flowNetwork)
# use this to save your result
self.maximumFlow = -1

Expand All @@ -93,7 +93,7 @@ def getMaximumFlow(self):

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)]

Expand Down
3 changes: 1 addition & 2 deletions graphs/graph_list.py
Original file line number Diff line number Diff line change
@@ -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 = {}

Expand Down
7 changes: 3 additions & 4 deletions hashes/hamming_code.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Author: João Gustavo A. Amorim & Gabriel Kunz
# Author email: [email protected] and [email protected]
# Coding date: apr 2019
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
5 changes: 2 additions & 3 deletions linear_algebra/src/lib.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 26 14:29:11 2018
Expand All @@ -25,7 +24,7 @@
import random


class Vector(object):
class Vector:
"""
This class represents a vector of arbitrary size.
You need to give the vector components.
Expand Down Expand Up @@ -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.
Expand Down
1 change: 0 additions & 1 deletion linear_algebra/src/test_linear_algebra.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 26 15:40:07 2018
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/k_means_clust.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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
)
)
Expand Down
1 change: 0 additions & 1 deletion machine_learning/logistic_regression.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

## Logistic Regression from scratch

Expand Down
6 changes: 2 additions & 4 deletions machine_learning/sequential_minimum_optimization.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
"""
Implementation of sequential minimal optimization(SMO) for support vector machines(SVM).
Expand Down Expand Up @@ -29,7 +28,6 @@
http://web.cs.iastate.edu/~honavar/smo-svm.pdf
"""

from __future__ import division

import os
import sys
Expand All @@ -44,7 +42,7 @@
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,
Expand Down Expand Up @@ -405,7 +403,7 @@ def length(self):
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)
Expand Down
Loading

0 comments on commit 28419cf

Please sign in to comment.