Skip to content

Commit

Permalink
Set the Python file maximum line length to 88 characters (TheAlgorith…
Browse files Browse the repository at this point in the history
…ms#2122)

* flake8 --max-line-length=88

* fixup! Format Python code with psf/black push

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
  • Loading branch information
cclauss and github-actions authored Jun 16, 2020
1 parent 9438c6b commit 9316e7c
Show file tree
Hide file tree
Showing 90 changed files with 474 additions and 321 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ notifications:
on_success: never
before_script:
- black --check . || true
- flake8 --ignore=E203,W503 --max-complexity=25 --max-line-length=120 --statistics --count .
- flake8 --ignore=E203,W503 --max-complexity=25 --max-line-length=88 --statistics --count .
- scripts/validate_filenames.py # no uppercase, no spaces, in a directory
- pip install -r requirements.txt # fast fail on black, flake8, validate_filenames
script:
Expand Down
8 changes: 5 additions & 3 deletions arithmetic_analysis/intersection.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import math


def intersection(
function, x0, x1
): # function is the f we want to find its root and x0 and x1 are two random starting points
def intersection(function, x0, x1):
"""
function is the f we want to find its root
x0 and x1 are two random starting points
"""
x_n = x0
x_n1 = x1
while True:
Expand Down
10 changes: 6 additions & 4 deletions backtracking/hamiltonian_cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ def valid_connection(
Checks whether it is possible to add next into path by validating 2 statements
1. There should be path between current and next vertex
2. Next vertex should not be in path
If both validations succeeds we return true saying that it is possible to connect this vertices
either we return false
If both validations succeeds we return True saying that it is possible to connect
this vertices either we return False
Case 1:Use exact graph as in main function, with initialized values
>>> graph = [[0, 1, 0, 1, 0],
Expand Down Expand Up @@ -52,7 +52,8 @@ def util_hamilton_cycle(graph: List[List[int]], path: List[int], curr_ind: int)
Pseudo-Code
Base Case:
1. Chceck if we visited all of vertices
1.1 If last visited vertex has path to starting vertex return True either return False
1.1 If last visited vertex has path to starting vertex return True either
return False
Recursive Step:
2. Iterate over each vertex
Check if next vertex is valid for transiting from current vertex
Expand All @@ -74,7 +75,8 @@ def util_hamilton_cycle(graph: List[List[int]], path: List[int], curr_ind: int)
>>> print(path)
[0, 1, 2, 4, 3, 0]
Case 2: Use exact graph as in previous case, but in the properties taken from middle of calculation
Case 2: Use exact graph as in previous case, but in the properties taken from
middle of calculation
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
Expand Down
8 changes: 4 additions & 4 deletions backtracking/n_queens.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@

def isSafe(board, row, column):
"""
This function returns a boolean value True if it is safe to place a queen there considering
the current state of the board.
This function returns a boolean value True if it is safe to place a queen there
considering the current state of the board.
Parameters :
board(2D matrix) : board
Expand Down Expand Up @@ -56,8 +56,8 @@ def solve(board, row):
return
for i in range(len(board)):
"""
For every row it iterates through each column to check if it is feasible to place a
queen there.
For every row it iterates through each column to check if it is feasible to
place a queen there.
If all the combinations for that particular branch are successful the board is
reinitialized for the next possible combination.
"""
Expand Down
12 changes: 7 additions & 5 deletions backtracking/sum_of_subsets.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""
The sum-of-subsetsproblem states that a set of non-negative integers, and a value M,
determine all possible subsets of the given set whose summation sum equal to given M.
The sum-of-subsetsproblem states that a set of non-negative integers, and a
value M, determine all possible subsets of the given set whose summation sum
equal to given M.
Summation of the chosen numbers must be equal to given number M and one number can
be used only once.
Summation of the chosen numbers must be equal to given number M and one number
can be used only once.
"""


Expand All @@ -21,7 +22,8 @@ def create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nu
Creates a state space tree to iterate through each branch using DFS.
It terminates the branching of a node when any of the two conditions
given below satisfy.
This algorithm follows depth-fist-search and backtracks when the node is not branchable.
This algorithm follows depth-fist-search and backtracks when the node is not
branchable.
"""
if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:
Expand Down
5 changes: 3 additions & 2 deletions blockchain/chinese_remainder_theorem.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# Chinese Remainder Theorem:
# GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor )

# If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b there exists integer n,
# such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are two such integers, then n1=n2(mod ab)
# If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b
# there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are
# two such integers, then n1=n2(mod ab)

# Algorithm :

Expand Down
18 changes: 11 additions & 7 deletions blockchain/diophantine_equation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the diophantine equation
# a*x + b*y = c has a solution (where x and y are integers) iff gcd(a,b) divides c.
# Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the
# diophantine equation a*x + b*y = c has a solution (where x and y are integers)
# iff gcd(a,b) divides c.

# GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor )

Expand Down Expand Up @@ -29,8 +30,9 @@ def diophantine(a, b, c):

# Finding All solutions of Diophantine Equations:

# Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of Diophantine Equation a*x + b*y = c.
# a*x0 + b*y0 = c, then all the solutions have the form a(x0 + t*q) + b(y0 - t*p) = c, where t is an arbitrary integer.
# Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of Diophantine
# Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the solutions have the form
# a(x0 + t*q) + b(y0 - t*p) = c, where t is an arbitrary integer.

# n is the number of solution you want, n = 2 by default

Expand Down Expand Up @@ -75,8 +77,9 @@ def greatest_common_divisor(a, b):
>>> greatest_common_divisor(7,5)
1
Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime
if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1.
Note : In number theory, two integers a and b are said to be relatively prime,
mutually prime, or co-prime if the only positive integer (factor) that
divides both of them is 1 i.e., gcd(a,b) = 1.
>>> greatest_common_divisor(121, 11)
11
Expand All @@ -91,7 +94,8 @@ def greatest_common_divisor(a, b):
return b


# Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b)
# Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers
# x and y, then d = gcd(a,b)


def extended_gcd(a, b):
Expand Down
12 changes: 7 additions & 5 deletions blockchain/modular_division.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

# GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor )

# Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should return an integer x such that
# 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)).
# Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should
# return an integer x such that 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)).

# Theorem:
# a has a multiplicative inverse modulo n iff gcd(a,n) = 1
Expand Down Expand Up @@ -68,7 +68,8 @@ def modular_division2(a, b, n):
return x


# Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b)
# Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x
# and y, then d = gcd(a,b)


def extended_gcd(a, b):
Expand Down Expand Up @@ -123,8 +124,9 @@ def greatest_common_divisor(a, b):
>>> greatest_common_divisor(7,5)
1
Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime
if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1.
Note : In number theory, two integers a and b are said to be relatively prime,
mutually prime, or co-prime if the only positive integer (factor) that divides
both of them is 1 i.e., gcd(a,b) = 1.
>>> greatest_common_divisor(121, 11)
11
Expand Down
6 changes: 4 additions & 2 deletions ciphers/affine_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ def check_keys(keyA, keyB, mode):

def encrypt_message(key: int, message: str) -> str:
"""
>>> encrypt_message(4545, 'The affine cipher is a type of monoalphabetic substitution cipher.')
>>> encrypt_message(4545, 'The affine cipher is a type of monoalphabetic '
... 'substitution cipher.')
'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi'
"""
keyA, keyB = divmod(key, len(SYMBOLS))
Expand All @@ -72,7 +73,8 @@ def encrypt_message(key: int, message: str) -> str:

def decrypt_message(key: int, message: str) -> str:
"""
>>> decrypt_message(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi')
>>> decrypt_message(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF'
... '{xIp~{HL}Gi')
'The affine cipher is a type of monoalphabetic substitution cipher.'
"""
keyA, keyB = divmod(key, len(SYMBOLS))
Expand Down
3 changes: 2 additions & 1 deletion ciphers/base64_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ def decode_base64(text):
'WELCOME to base64 encoding 😁'
>>> decode_base64('QcOF4ZCD8JCAj/CfpJM=')
'AÅᐃ𐀏🤓'
>>> decode_base64("QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\r\nQUFB")
>>> decode_base64("QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUF"
... "BQUFBQUFBQUFB\r\nQUFB")
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
"""
base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
Expand Down
3 changes: 2 additions & 1 deletion ciphers/elgamal_key_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ def main():

# I have written my code naively same as definition of primitive root
# however every time I run this program, memory exceeded...
# so I used 4.80 Algorithm in Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996)
# so I used 4.80 Algorithm in
# Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996)
# and it seems to run nicely!
def primitiveRoot(p_val):
print("Generating primitive root of p")
Expand Down
3 changes: 2 additions & 1 deletion ciphers/hill_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ def check_determinant(self) -> None:
req_l = len(self.key_string)
if greatest_common_divisor(det, len(self.key_string)) != 1:
raise ValueError(
f"determinant modular {req_l} of encryption key({det}) is not co prime w.r.t {req_l}.\nTry another key."
f"determinant modular {req_l} of encryption key({det}) is not co prime "
f"w.r.t {req_l}.\nTry another key."
)

def process_text(self, text: str) -> str:
Expand Down
21 changes: 13 additions & 8 deletions ciphers/shuffled_shift_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,27 +83,30 @@ def __make_key_list(self) -> list:
Shuffling only 26 letters of the english alphabet can generate 26!
combinations for the shuffled list. In the program we consider, a set of
97 characters (including letters, digits, punctuation and whitespaces),
thereby creating a possibility of 97! combinations (which is a 152 digit number in itself),
thus diminishing the possibility of a brute force approach. Moreover,
shift keys even introduce a multiple of 26 for a brute force approach
thereby creating a possibility of 97! combinations (which is a 152 digit number
in itself), thus diminishing the possibility of a brute force approach.
Moreover, shift keys even introduce a multiple of 26 for a brute force approach
for each of the already 97! combinations.
"""
# key_list_options contain nearly all printable except few elements from string.whitespace
# key_list_options contain nearly all printable except few elements from
# string.whitespace
key_list_options = (
string.ascii_letters + string.digits + string.punctuation + " \t\n"
)

keys_l = []

# creates points known as breakpoints to break the key_list_options at those points and pivot each substring
# creates points known as breakpoints to break the key_list_options at those
# points and pivot each substring
breakpoints = sorted(set(self.__passcode))
temp_list = []

# algorithm for creating a new shuffled list, keys_l, out of key_list_options
for i in key_list_options:
temp_list.extend(i)

# checking breakpoints at which to pivot temporary sublist and add it into keys_l
# checking breakpoints at which to pivot temporary sublist and add it into
# keys_l
if i in breakpoints or i == key_list_options[-1]:
keys_l.extend(temp_list[::-1])
temp_list = []
Expand Down Expand Up @@ -131,7 +134,8 @@ def decrypt(self, encoded_message: str) -> str:
"""
decoded_message = ""

# decoding shift like Caesar cipher algorithm implementing negative shift or reverse shift or left shift
# decoding shift like Caesar cipher algorithm implementing negative shift or
# reverse shift or left shift
for i in encoded_message:
position = self.__key_list.index(i)
decoded_message += self.__key_list[
Expand All @@ -152,7 +156,8 @@ def encrypt(self, plaintext: str) -> str:
"""
encoded_message = ""

# encoding shift like Caesar cipher algorithm implementing positive shift or forward shift or right shift
# encoding shift like Caesar cipher algorithm implementing positive shift or
# forward shift or right shift
for i in plaintext:
position = self.__key_list.index(i)
encoded_message += self.__key_list[
Expand Down
6 changes: 4 additions & 2 deletions compression/peak_signal_to_noise_ratio.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""
Peak signal-to-noise ratio - PSNR - https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
Source: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python/
Peak signal-to-noise ratio - PSNR
https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
Source:
https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python
"""

import math
Expand Down
7 changes: 4 additions & 3 deletions conversions/decimal_to_any.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,10 @@ def decimal_to_any(num: int, base: int) -> str:
if base > 36:
raise ValueError("base must be <= 36")
# fmt: off
ALPHABET_VALUES = {'10': 'A', '11': 'B', '12': 'C', '13': 'D', '14': 'E', '15': 'F', '16': 'G', '17': 'H',
'18': 'I', '19': 'J', '20': 'K', '21': 'L', '22': 'M', '23': 'N', '24': 'O', '25': 'P',
'26': 'Q', '27': 'R', '28': 'S', '29': 'T', '30': 'U', '31': 'V', '32': 'W', '33': 'X',
ALPHABET_VALUES = {'10': 'A', '11': 'B', '12': 'C', '13': 'D', '14': 'E', '15': 'F',
'16': 'G', '17': 'H', '18': 'I', '19': 'J', '20': 'K', '21': 'L',
'22': 'M', '23': 'N', '24': 'O', '25': 'P', '26': 'Q', '27': 'R',
'28': 'S', '29': 'T', '30': 'U', '31': 'V', '32': 'W', '33': 'X',
'34': 'Y', '35': 'Z'}
# fmt: on
new_value = ""
Expand Down
3 changes: 2 additions & 1 deletion conversions/decimal_to_hexadecimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@

def decimal_to_hexadecimal(decimal):
"""
take integer decimal value, return hexadecimal representation as str beginning with 0x
take integer decimal value, return hexadecimal representation as str beginning
with 0x
>>> decimal_to_hexadecimal(5)
'0x5'
>>> decimal_to_hexadecimal(15)
Expand Down
3 changes: 2 additions & 1 deletion conversions/decimal_to_octal.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
def decimal_to_octal(num: int) -> str:
"""Convert a Decimal Number to an Octal Number.
>>> all(decimal_to_octal(i) == oct(i) for i in (0, 2, 8, 64, 65, 216, 255, 256, 512))
>>> all(decimal_to_octal(i) == oct(i) for i
... in (0, 2, 8, 64, 65, 216, 255, 256, 512))
True
"""
octal = 0
Expand Down
21 changes: 15 additions & 6 deletions data_structures/data_structures/heap/heap_generic.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
class Heap:
"""A generic Heap class, can be used as min or max by passing the key function accordingly.
"""
A generic Heap class, can be used as min or max by passing the key function
accordingly.
"""

def __init__(self, key=None):
Expand All @@ -9,7 +11,8 @@ def __init__(self, key=None):
self.pos_map = {}
# Stores current size of heap.
self.size = 0
# Stores function used to evaluate the score of an item on which basis ordering will be done.
# Stores function used to evaluate the score of an item on which basis ordering
# will be done.
self.key = key or (lambda x: x)

def _parent(self, i):
Expand Down Expand Up @@ -41,7 +44,10 @@ def _cmp(self, i, j):
return self.arr[i][1] < self.arr[j][1]

def _get_valid_parent(self, i):
"""Returns index of valid parent as per desired ordering among given index and both it's children"""
"""
Returns index of valid parent as per desired ordering among given index and
both it's children
"""
left = self._left(i)
right = self._right(i)
valid_parent = i
Expand Down Expand Up @@ -87,8 +93,8 @@ def delete_item(self, item):
self.arr[index] = self.arr[self.size - 1]
self.pos_map[self.arr[self.size - 1][0]] = index
self.size -= 1
# Make sure heap is right in both up and down direction.
# Ideally only one of them will make any change- so no performance loss in calling both.
# Make sure heap is right in both up and down direction. Ideally only one
# of them will make any change- so no performance loss in calling both.
if self.size > index:
self._heapify_up(index)
self._heapify_down(index)
Expand All @@ -109,7 +115,10 @@ def get_top(self):
return self.arr[0] if self.size else None

def extract_top(self):
"""Returns top item tuple (Calculated value, item) from heap and removes it as well if present"""
"""
Return top item tuple (Calculated value, item) from heap and removes it as well
if present
"""
top_item_tuple = self.get_top()
if top_item_tuple:
self.delete_item(top_item_tuple[0])
Expand Down
Loading

0 comments on commit 9316e7c

Please sign in to comment.