Skip to content

Commit

Permalink
Optimized recursive_bubble_sort (TheAlgorithms#2410)
Browse files Browse the repository at this point in the history
* optimized recursive_bubble_sort

* Fixed doctest error due whitespace

* reduce loop times for optimization

* fixup! Format Python code with psf/black push

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
  • Loading branch information
realDuYuanChao and github-actions authored Sep 10, 2020
1 parent 25946e4 commit 4d0a8f2
Show file tree
Hide file tree
Showing 60 changed files with 934 additions and 893 deletions.
6 changes: 5 additions & 1 deletion arithmetic_analysis/newton_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@


# function is the f(x) and derivative is the f'(x)
def newton(function: RealFunc, derivative: RealFunc, starting_int: int,) -> float:
def newton(
function: RealFunc,
derivative: RealFunc,
starting_int: int,
) -> float:
"""
>>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3)
2.0945514815423474
Expand Down
2 changes: 1 addition & 1 deletion arithmetic_analysis/newton_raphson.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


def newton_raphson(func: str, a: int, precision: int = 10 ** -10) -> float:
""" Finds root from the point 'a' onwards by Newton-Raphson method
"""Finds root from the point 'a' onwards by Newton-Raphson method
>>> newton_raphson("sin(x)", 2)
3.1415926536808043
>>> newton_raphson("x**2 - 5*x +2", 0.4)
Expand Down
8 changes: 4 additions & 4 deletions backtracking/all_permutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ def generate_all_permutations(sequence):

def create_state_space_tree(sequence, current_sequence, index, index_used):
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly len(sequence) - index children.
It terminates when it reaches the end of the given sequence.
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly len(sequence) - index children.
It terminates when it reaches the end of the given sequence.
"""

if index == len(sequence):
print(current_sequence)
Expand Down
8 changes: 4 additions & 4 deletions backtracking/all_subsequences.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ def generate_all_subsequences(sequence):

def create_state_space_tree(sequence, current_subsequence, index):
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly two children.
It terminates when it reaches the end of the given sequence.
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly two children.
It terminates when it reaches the end of the given sequence.
"""

if index == len(sequence):
print(current_subsequence)
Expand Down
2 changes: 1 addition & 1 deletion backtracking/sudoku.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def sudoku(grid):
[7, 4, 5, 2, 8, 6, 3, 1, 9]]
>>> sudoku(no_solution)
False
"""
"""

if is_completed(grid):
return grid
Expand Down
12 changes: 6 additions & 6 deletions backtracking/sum_of_subsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ def generate_sum_of_subsets_soln(nums, max_sum):

def create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum):
"""
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.
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.
"""
"""
if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:
return
if sum(path) == max_sum:
Expand Down
10 changes: 5 additions & 5 deletions blockchain/modular_division.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,13 @@ def modular_division2(a, b, n):

def extended_gcd(a, b):
"""
>>> extended_gcd(10, 6)
(2, -1, 2)
>>> extended_gcd(10, 6)
(2, -1, 2)
>>> extended_gcd(7, 5)
(1, -2, 3)
>>> extended_gcd(7, 5)
(1, -2, 3)
** extended_gcd function is used when d = gcd(a,b) is required in output
** extended_gcd function is used when d = gcd(a,b) is required in output
"""
assert a >= 0 and b >= 0
Expand Down
102 changes: 67 additions & 35 deletions ciphers/enigma_machine2.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,50 @@

# used alphabet --------------------------
# from string.ascii_uppercase
abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

# -------------------------- default selection --------------------------
# rotors --------------------------
rotor1 = 'EGZWVONAHDCLFQMSIPJBYUKXTR'
rotor2 = 'FOBHMDKEXQNRAULPGSJVTYICZW'
rotor3 = 'ZJXESIUQLHAVRMDOYGTNFWPBKC'
rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR"
rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW"
rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC"
# reflector --------------------------
reflector = {'A': 'N', 'N': 'A', 'B': 'O', 'O': 'B', 'C': 'P', 'P': 'C', 'D': 'Q',
'Q': 'D', 'E': 'R', 'R': 'E', 'F': 'S', 'S': 'F', 'G': 'T', 'T': 'G',
'H': 'U', 'U': 'H', 'I': 'V', 'V': 'I', 'J': 'W', 'W': 'J', 'K': 'X',
'X': 'K', 'L': 'Y', 'Y': 'L', 'M': 'Z', 'Z': 'M'}
reflector = {
"A": "N",
"N": "A",
"B": "O",
"O": "B",
"C": "P",
"P": "C",
"D": "Q",
"Q": "D",
"E": "R",
"R": "E",
"F": "S",
"S": "F",
"G": "T",
"T": "G",
"H": "U",
"U": "H",
"I": "V",
"V": "I",
"J": "W",
"W": "J",
"K": "X",
"X": "K",
"L": "Y",
"Y": "L",
"M": "Z",
"Z": "M",
}

# -------------------------- extra rotors --------------------------
rotor4 = 'RMDJXFUWGISLHVTCQNKYPBEZOA'
rotor5 = 'SGLCPQWZHKXAREONTFBVIYJUDM'
rotor6 = 'HVSICLTYKQUBXDWAJZOMFGPREN'
rotor7 = 'RZWQHFMVDBKICJLNTUXAGYPSOE'
rotor8 = 'LFKIJODBEGAMQPXVUHYSTCZRWN'
rotor9 = 'KOAEGVDHXPQZMLFTYWJNBRCIUS'
rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA"
rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM"
rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN"
rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE"
rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN"
rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS"


def _validator(rotpos: tuple, rotsel: tuple, pb: str) -> tuple:
Expand All @@ -57,19 +81,22 @@ def _validator(rotpos: tuple, rotsel: tuple, pb: str) -> tuple:

unique_rotsel = len(set(rotsel))
if unique_rotsel < 3:
raise Exception(f'Please use 3 unique rotors (not {unique_rotsel})')
raise Exception(f"Please use 3 unique rotors (not {unique_rotsel})")

# Checks if rotor positions are valid
rotorpos1, rotorpos2, rotorpos3 = rotpos
if not 0 < rotorpos1 <= len(abc):
raise ValueError(f'First rotor position is not within range of 1..26 ('
f'{rotorpos1}')
raise ValueError(
f"First rotor position is not within range of 1..26 (" f"{rotorpos1}"
)
if not 0 < rotorpos2 <= len(abc):
raise ValueError(f'Second rotor position is not within range of 1..26 ('
f'{rotorpos2})')
raise ValueError(
f"Second rotor position is not within range of 1..26 (" f"{rotorpos2})"
)
if not 0 < rotorpos3 <= len(abc):
raise ValueError(f'Third rotor position is not within range of 1..26 ('
f'{rotorpos3})')
raise ValueError(
f"Third rotor position is not within range of 1..26 (" f"{rotorpos3})"
)

# Validates string and returns dict
pb = _plugboard(pb)
Expand Down Expand Up @@ -97,21 +124,21 @@ def _plugboard(pbstring: str) -> dict:
# a) is type string
# b) has even length (so pairs can be made)
if not isinstance(pbstring, str):
raise TypeError(f'Plugboard setting isn\'t type string ({type(pbstring)})')
raise TypeError(f"Plugboard setting isn't type string ({type(pbstring)})")
elif len(pbstring) % 2 != 0:
raise Exception(f'Odd number of symbols ({len(pbstring)})')
elif pbstring == '':
raise Exception(f"Odd number of symbols ({len(pbstring)})")
elif pbstring == "":
return {}

pbstring.replace(' ', '')
pbstring.replace(" ", "")

# Checks if all characters are unique
tmppbl = set()
for i in pbstring:
if i not in abc:
raise Exception(f'\'{i}\' not in list of symbols')
raise Exception(f"'{i}' not in list of symbols")
elif i in tmppbl:
raise Exception(f'Duplicate symbol ({i})')
raise Exception(f"Duplicate symbol ({i})")
else:
tmppbl.add(i)
del tmppbl
Expand All @@ -125,8 +152,12 @@ def _plugboard(pbstring: str) -> dict:
return pb


def enigma(text: str, rotor_position: tuple,
rotor_selection: tuple = (rotor1, rotor2, rotor3), plugb: str = '') -> str:
def enigma(
text: str,
rotor_position: tuple,
rotor_selection: tuple = (rotor1, rotor2, rotor3),
plugb: str = "",
) -> str:
"""
The only difference with real-world enigma is that I allowed string input.
All characters are converted to uppercase. (non-letter symbol are ignored)
Expand Down Expand Up @@ -179,7 +210,8 @@ def enigma(text: str, rotor_position: tuple,

text = text.upper()
rotor_position, rotor_selection, plugboard = _validator(
rotor_position, rotor_selection, plugb.upper())
rotor_position, rotor_selection, plugb.upper()
)

rotorpos1, rotorpos2, rotorpos3 = rotor_position
rotor1, rotor2, rotor3 = rotor_selection
Expand Down Expand Up @@ -245,12 +277,12 @@ def enigma(text: str, rotor_position: tuple,
return "".join(result)


if __name__ == '__main__':
message = 'This is my Python script that emulates the Enigma machine from WWII.'
if __name__ == "__main__":
message = "This is my Python script that emulates the Enigma machine from WWII."
rotor_pos = (1, 1, 1)
pb = 'pictures'
pb = "pictures"
rotor_sel = (rotor2, rotor4, rotor8)
en = enigma(message, rotor_pos, rotor_sel, pb)

print('Encrypted message:', en)
print('Decrypted message:', enigma(en, rotor_pos, rotor_sel, pb))
print("Encrypted message:", en)
print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
70 changes: 35 additions & 35 deletions ciphers/xor_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,20 @@
class XORCipher:
def __init__(self, key=0):
"""
simple constructor that receives a key or uses
default key = 0
"""
simple constructor that receives a key or uses
default key = 0
"""

# private field
self.__key = key

def encrypt(self, content, key):
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
Expand All @@ -55,11 +55,11 @@ def encrypt(self, content, key):

def decrypt(self, content, key):
"""
input: 'content' of type list and 'key' of type int
output: decrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
input: 'content' of type list and 'key' of type int
output: decrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""

# precondition
assert isinstance(key, int) and isinstance(content, list)
Expand All @@ -80,11 +80,11 @@ def decrypt(self, content, key):

def encrypt_string(self, content, key=0):
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
Expand All @@ -105,11 +105,11 @@ def encrypt_string(self, content, key=0):

def decrypt_string(self, content, key=0):
"""
input: 'content' of type string and 'key' of type int
output: decrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
input: 'content' of type string and 'key' of type int
output: decrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""

# precondition
assert isinstance(key, int) and isinstance(content, str)
Expand All @@ -130,12 +130,12 @@ def decrypt_string(self, content, key=0):

def encrypt_file(self, file, key=0):
"""
input: filename (str) and a key (int)
output: returns true if encrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
input: filename (str) and a key (int)
output: returns true if encrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
Expand All @@ -155,12 +155,12 @@ def encrypt_file(self, file, key=0):

def decrypt_file(self, file, key):
"""
input: filename (str) and a key (int)
output: returns true if decrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
input: filename (str) and a key (int)
output: returns true if decrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""

# precondition
assert isinstance(file, str) and isinstance(key, int)
Expand Down
Loading

0 comments on commit 4d0a8f2

Please sign in to comment.