Skip to content

Commit 28419cf

Browse files
cclausspoyea
authored andcommitted
pyupgrade --py37-plus **/*.py (TheAlgorithms#1654)
* pyupgrade --py37-plus **/*.py * fixup! Format Python code with psf/black push
1 parent 34c808b commit 28419cf

File tree

77 files changed

+71
-128
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

77 files changed

+71
-128
lines changed

backtracking/all_combinations.py

-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
31
"""
42
In this problem, we want to determine all possible combinations of k
53
numbers out of 1 ... n. We use backtracking to solve this problem.

ciphers/brute_force_caesar_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def decrypt(message):
4040
translated = translated + LETTERS[num]
4141
else:
4242
translated = translated + symbol
43-
print("Decryption using Key #%s: %s" % (key, translated))
43+
print(f"Decryption using Key #{key}: {translated}")
4444

4545

4646
def main():

ciphers/hill_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def checkDeterminant(self):
7878
req_l = len(self.key_string)
7979
if gcd(det, len(self.key_string)) != 1:
8080
raise ValueError(
81-
"discriminant modular {0} of encryption key({1}) is not co prime w.r.t {2}.\nTry another key.".format(
81+
"discriminant modular {} of encryption key({}) is not co prime w.r.t {}.\nTry another key.".format(
8282
req_l, det, req_l
8383
)
8484
)

ciphers/rsa_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def encryptAndWriteToFile(
101101
for i in range(len(encryptedBlocks)):
102102
encryptedBlocks[i] = str(encryptedBlocks[i])
103103
encryptedContent = ",".join(encryptedBlocks)
104-
encryptedContent = "%s_%s_%s" % (len(message), blockSize, encryptedContent)
104+
encryptedContent = "{}_{}_{}".format(len(message), blockSize, encryptedContent)
105105
with open(messageFilename, "w") as fo:
106106
fo.write(encryptedContent)
107107
return encryptedContent

ciphers/rsa_key_generator.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,11 @@ def makeKeyFiles(name, keySize):
4343
publicKey, privateKey = generateKey(keySize)
4444
print("\nWriting public key to file %s_pubkey.txt..." % name)
4545
with open("%s_pubkey.txt" % name, "w") as fo:
46-
fo.write("%s,%s,%s" % (keySize, publicKey[0], publicKey[1]))
46+
fo.write("{},{},{}".format(keySize, publicKey[0], publicKey[1]))
4747

4848
print("Writing private key to file %s_privkey.txt..." % name)
4949
with open("%s_privkey.txt" % name, "w") as fo:
50-
fo.write("%s,%s,%s" % (keySize, privateKey[0], privateKey[1]))
50+
fo.write("{},{},{}".format(keySize, privateKey[0], privateKey[1]))
5151

5252

5353
if __name__ == "__main__":

ciphers/shuffled_shift_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import string
33

44

5-
class ShuffledShiftCipher(object):
5+
class ShuffledShiftCipher:
66
"""
77
This algorithm uses the Caesar Cipher algorithm but removes the option to
88
use brute force to decrypt the message.

ciphers/simple_substitution_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def main():
1717
mode = "decrypt"
1818
translated = decryptMessage(key, message)
1919

20-
print("\n%sion: \n%s" % (mode.title(), translated))
20+
print("\n{}ion: \n{}".format(mode.title(), translated))
2121

2222

2323
def checkValidKey(key):

ciphers/xor_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
"""
1919

2020

21-
class XORCipher(object):
21+
class XORCipher:
2222
def __init__(self, key=0):
2323
"""
2424
simple constructor that receives a key or uses

compression/burrows_wheeler.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -135,16 +135,14 @@ def reverse_bwt(bwt_string: str, idx_original_string: int) -> str:
135135
idx_original_string = int(idx_original_string)
136136
except ValueError:
137137
raise TypeError(
138-
(
139-
"The parameter idx_original_string type must be int or passive"
140-
" of cast to int."
141-
)
138+
"The parameter idx_original_string type must be int or passive"
139+
" of cast to int."
142140
)
143141
if idx_original_string < 0:
144142
raise ValueError("The parameter idx_original_string must not be lower than 0.")
145143
if idx_original_string >= len(bwt_string):
146144
raise ValueError(
147-
("The parameter idx_original_string must be lower than" " len(bwt_string).")
145+
"The parameter idx_original_string must be lower than" " len(bwt_string)."
148146
)
149147

150148
ordered_rotations = [""] * len(bwt_string)

data_structures/binary_tree/avl_tree.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
An auto-balanced binary tree!
43
"""

data_structures/binary_tree/red_black_tree.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ def __repr__(self):
467467
from pprint import pformat
468468

469469
if self.left is None and self.right is None:
470-
return "'%s %s'" % (self.label, (self.color and "red") or "blk")
470+
return "'{} {}'".format(self.label, (self.color and "red") or "blk")
471471
return pformat(
472472
{
473473
"%s %s"

data_structures/binary_tree/treap.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from typing import Tuple
33

44

5-
class Node(object):
5+
class Node:
66
"""
77
Treap's node
88
Treap is a binary tree by value and heap by priority
@@ -18,11 +18,10 @@ def __repr__(self):
1818
from pprint import pformat
1919

2020
if self.left is None and self.right is None:
21-
return "'%s: %.5s'" % (self.value, self.prior)
21+
return f"'{self.value}: {self.prior:.5}'"
2222
else:
2323
return pformat(
24-
{"%s: %.5s" % (self.value, self.prior): (self.left, self.right)},
25-
indent=1,
24+
{f"{self.value}: {self.prior:.5}": (self.left, self.right)}, indent=1,
2625
)
2726

2827
def __str__(self):

data_structures/data_structures/heap/heap_generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
class Heap(object):
1+
class Heap:
22
"""A generic Heap class, can be used as min or max by passing the key function accordingly.
33
"""
44

data_structures/hashing/hash_table.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def hash_function(self, key):
2828

2929
def _step_by_step(self, step_ord):
3030

31-
print("step {0}".format(step_ord))
31+
print(f"step {step_ord}")
3232
print([i for i in range(len(self.values))])
3333
print(self.values)
3434

data_structures/stacks/stack.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
__author__ = "Omkar Pathak"
22

33

4-
class Stack(object):
4+
class Stack:
55
""" A stack is an abstract data type that serves as a collection of
66
elements with two principal operations: push() and pop(). push() adds an
77
element to the top of the stack, and pop() removes an element from the top

digital_image_processing/histogram_equalization/histogram_stretch.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
Created on Fri Sep 28 15:22:29 2018
43

digital_image_processing/index_calculation.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -389,10 +389,7 @@ def Hue(self):
389389
:return: index
390390
"""
391391
return np.arctan(
392-
(
393-
((2 * self.red - self.green - self.blue) / 30.5)
394-
* (self.green - self.blue)
395-
)
392+
((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue)
396393
)
397394

398395
def IVI(self, a=None, b=None):

dynamic_programming/fast_fibonacci.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/python
2-
# encoding=utf8
32

43
"""
54
This program calculates the nth Fibonacci number in O(log(n)).

dynamic_programming/k_means_clustering_tensorflow.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def TFKMeansCluster(vectors, noofclusters):
4040
##First lets ensure we have a Variable vector for each centroid,
4141
##initialized to one of the vectors from the available data points
4242
centroids = [
43-
tf.Variable((vectors[vector_indices[i]])) for i in range(noofclusters)
43+
tf.Variable(vectors[vector_indices[i]]) for i in range(noofclusters)
4444
]
4545
##These nodes will assign the centroid Variables the appropriate
4646
##values

dynamic_programming/matrix_chain_order.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def main():
4646
# 30*35 35*15 15*5 5*10 10*20 20*25
4747
Matrix, OptimalSolution = MatrixChainOrder(array)
4848

49-
print("No. of Operation required: " + str((Matrix[1][n - 1])))
49+
print("No. of Operation required: " + str(Matrix[1][n - 1]))
5050
PrintOptimalSolution(OptimalSolution, 1, n - 1)
5151

5252

graphs/basic_graphs.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848

4949

5050
def dfs(G, s):
51-
vis, S = set([s]), [s]
51+
vis, S = {s}, [s]
5252
print(s)
5353
while S:
5454
flag = 0
@@ -76,7 +76,7 @@ def dfs(G, s):
7676

7777

7878
def bfs(G, s):
79-
vis, Q = set([s]), deque([s])
79+
vis, Q = {s}, deque([s])
8080
print(s)
8181
while Q:
8282
u = Q.popleft()
@@ -255,7 +255,7 @@ def krusk(E_and_n):
255255
# Sort edges on the basis of distance
256256
(E, n) = E_and_n
257257
E.sort(reverse=True, key=lambda x: x[2])
258-
s = [set([i]) for i in range(1, n + 1)]
258+
s = [{i} for i in range(1, n + 1)]
259259
while True:
260260
if len(s) == 1:
261261
break

graphs/breadth_first_search.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/python
2-
# encoding=utf8
32

43
""" Author: OMKAR PATHAK """
54

graphs/depth_first_search.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/python
2-
# encoding=utf8
32

43
""" Author: OMKAR PATHAK """
54

graphs/edmonds_karp_multiple_source_and_sink.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def setMaximumFlowAlgorithm(self, Algorithm):
5757
self.maximumFlowAlgorithm = Algorithm(self)
5858

5959

60-
class FlowNetworkAlgorithmExecutor(object):
60+
class FlowNetworkAlgorithmExecutor:
6161
def __init__(self, flowNetwork):
6262
self.flowNetwork = flowNetwork
6363
self.verticesCount = flowNetwork.verticesCount
@@ -80,7 +80,7 @@ def _algorithm(self):
8080

8181
class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor):
8282
def __init__(self, flowNetwork):
83-
super(MaximumFlowAlgorithmExecutor, self).__init__(flowNetwork)
83+
super().__init__(flowNetwork)
8484
# use this to save your result
8585
self.maximumFlow = -1
8686

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

9494
class PushRelabelExecutor(MaximumFlowAlgorithmExecutor):
9595
def __init__(self, flowNetwork):
96-
super(PushRelabelExecutor, self).__init__(flowNetwork)
96+
super().__init__(flowNetwork)
9797

9898
self.preflow = [[0] * self.verticesCount for i in range(self.verticesCount)]
9999

graphs/graph_list.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
#!/usr/bin/python
2-
# encoding=utf8
32

43
# Author: OMKAR PATHAK
54

65
# We can use Python's dictionary for constructing the graph.
76

87

9-
class AdjacencyList(object):
8+
class AdjacencyList:
109
def __init__(self):
1110
self.List = {}
1211

hashes/hamming_code.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
# Author: João Gustavo A. Amorim & Gabriel Kunz
32
# Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br
43
# Coding date: apr 2019
@@ -100,7 +99,7 @@ def emitterConverter(sizePar, data):
10099
# Performs a template of bit positions - who should be given,
101100
# and who should be parity
102101
if qtdBP < sizePar:
103-
if ((np.log(x) / np.log(2))).is_integer():
102+
if (np.log(x) / np.log(2)).is_integer():
104103
dataOutGab.append("P")
105104
qtdBP = qtdBP + 1
106105
else:
@@ -170,7 +169,7 @@ def receptorConverter(sizePar, data):
170169
# Performs a template of bit positions - who should be given,
171170
# and who should be parity
172171
if qtdBP < sizePar:
173-
if ((np.log(x) / np.log(2))).is_integer():
172+
if (np.log(x) / np.log(2)).is_integer():
174173
dataOutGab.append("P")
175174
qtdBP = qtdBP + 1
176175
else:
@@ -204,7 +203,7 @@ def receptorConverter(sizePar, data):
204203
# Performs a template position of bits - who should be given,
205204
# and who should be parity
206205
if qtdBP < sizePar:
207-
if ((np.log(x) / np.log(2))).is_integer():
206+
if (np.log(x) / np.log(2)).is_integer():
208207
dataOutGab.append("P")
209208
qtdBP = qtdBP + 1
210209
else:

linear_algebra/src/lib.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
Created on Mon Feb 26 14:29:11 2018
43
@@ -25,7 +24,7 @@
2524
import random
2625

2726

28-
class Vector(object):
27+
class Vector:
2928
"""
3029
This class represents a vector of arbitrary size.
3130
You need to give the vector components.
@@ -205,7 +204,7 @@ def randomVector(N, a, b):
205204
return Vector(ans)
206205

207206

208-
class Matrix(object):
207+
class Matrix:
209208
"""
210209
class: Matrix
211210
This class represents a arbitrary matrix.

linear_algebra/src/test_linear_algebra.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
Created on Mon Feb 26 15:40:07 2018
43

machine_learning/k_means_clust.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ def plot_heterogeneity(heterogeneity, k):
126126
plt.plot(heterogeneity, linewidth=4)
127127
plt.xlabel("# Iterations")
128128
plt.ylabel("Heterogeneity")
129-
plt.title("Heterogeneity of clustering over time, K={0:d}".format(k))
129+
plt.title(f"Heterogeneity of clustering over time, K={k:d}")
130130
plt.rcParams.update({"font.size": 16})
131131
plt.show()
132132

@@ -164,7 +164,7 @@ def kmeans(
164164
num_changed = np.sum(prev_cluster_assignment != cluster_assignment)
165165
if verbose:
166166
print(
167-
" {0:5d} elements changed their cluster assignment.".format(
167+
" {:5d} elements changed their cluster assignment.".format(
168168
num_changed
169169
)
170170
)

machine_learning/logistic_regression.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/python
2-
# -*- coding: utf-8 -*-
32

43
## Logistic Regression from scratch
54

machine_learning/sequential_minimum_optimization.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# coding: utf-8
21
"""
32
Implementation of sequential minimal optimization(SMO) for support vector machines(SVM).
43
@@ -29,7 +28,6 @@
2928
http://web.cs.iastate.edu/~honavar/smo-svm.pdf
3029
"""
3130

32-
from __future__ import division
3331

3432
import os
3533
import sys
@@ -44,7 +42,7 @@
4442
CANCER_DATASET_URL = "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data"
4543

4644

47-
class SmoSVM(object):
45+
class SmoSVM:
4846
def __init__(
4947
self,
5048
train,
@@ -405,7 +403,7 @@ def length(self):
405403
return self.samples.shape[0]
406404

407405

408-
class Kernel(object):
406+
class Kernel:
409407
def __init__(self, kernel, degree=1.0, coef0=0.0, gamma=1.0):
410408
self.degree = np.float64(degree)
411409
self.coef0 = np.float64(coef0)

0 commit comments

Comments
 (0)