mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Optimized recursive_bubble_sort (#2410)
* 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>
This commit is contained in:
parent
25946e4570
commit
4d0a8f2355
|
@ -7,7 +7,11 @@ RealFunc = Callable[[float], float] # type alias for a real -> real function
|
||||||
|
|
||||||
|
|
||||||
# function is the f(x) and derivative is the f'(x)
|
# 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)
|
>>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3)
|
||||||
2.0945514815423474
|
2.0945514815423474
|
||||||
|
|
|
@ -9,7 +9,7 @@ from sympy import diff
|
||||||
|
|
||||||
|
|
||||||
def newton_raphson(func: str, a: int, precision: int = 10 ** -10) -> float:
|
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)
|
>>> newton_raphson("sin(x)", 2)
|
||||||
3.1415926536808043
|
3.1415926536808043
|
||||||
>>> newton_raphson("x**2 - 5*x +2", 0.4)
|
>>> newton_raphson("x**2 - 5*x +2", 0.4)
|
||||||
|
|
|
@ -13,10 +13,10 @@ def generate_all_permutations(sequence):
|
||||||
|
|
||||||
def create_state_space_tree(sequence, current_sequence, index, index_used):
|
def create_state_space_tree(sequence, current_sequence, index, index_used):
|
||||||
"""
|
"""
|
||||||
Creates a state space tree to iterate through each branch using DFS.
|
Creates a state space tree to iterate through each branch using DFS.
|
||||||
We know that each state has exactly len(sequence) - index children.
|
We know that each state has exactly len(sequence) - index children.
|
||||||
It terminates when it reaches the end of the given sequence.
|
It terminates when it reaches the end of the given sequence.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if index == len(sequence):
|
if index == len(sequence):
|
||||||
print(current_sequence)
|
print(current_sequence)
|
||||||
|
|
|
@ -13,10 +13,10 @@ def generate_all_subsequences(sequence):
|
||||||
|
|
||||||
def create_state_space_tree(sequence, current_subsequence, index):
|
def create_state_space_tree(sequence, current_subsequence, index):
|
||||||
"""
|
"""
|
||||||
Creates a state space tree to iterate through each branch using DFS.
|
Creates a state space tree to iterate through each branch using DFS.
|
||||||
We know that each state has exactly two children.
|
We know that each state has exactly two children.
|
||||||
It terminates when it reaches the end of the given sequence.
|
It terminates when it reaches the end of the given sequence.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if index == len(sequence):
|
if index == len(sequence):
|
||||||
print(current_subsequence)
|
print(current_subsequence)
|
||||||
|
|
|
@ -105,7 +105,7 @@ def sudoku(grid):
|
||||||
[7, 4, 5, 2, 8, 6, 3, 1, 9]]
|
[7, 4, 5, 2, 8, 6, 3, 1, 9]]
|
||||||
>>> sudoku(no_solution)
|
>>> sudoku(no_solution)
|
||||||
False
|
False
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if is_completed(grid):
|
if is_completed(grid):
|
||||||
return grid
|
return grid
|
||||||
|
|
|
@ -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):
|
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.
|
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
|
It terminates the branching of a node when any of the two conditions
|
||||||
given below satisfy.
|
given below satisfy.
|
||||||
This algorithm follows depth-fist-search and backtracks when the node is not
|
This algorithm follows depth-fist-search and backtracks when the node is not
|
||||||
branchable.
|
branchable.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:
|
if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:
|
||||||
return
|
return
|
||||||
if sum(path) == max_sum:
|
if sum(path) == max_sum:
|
||||||
|
|
|
@ -74,13 +74,13 @@ def modular_division2(a, b, n):
|
||||||
|
|
||||||
def extended_gcd(a, b):
|
def extended_gcd(a, b):
|
||||||
"""
|
"""
|
||||||
>>> extended_gcd(10, 6)
|
>>> extended_gcd(10, 6)
|
||||||
(2, -1, 2)
|
(2, -1, 2)
|
||||||
|
|
||||||
>>> extended_gcd(7, 5)
|
>>> extended_gcd(7, 5)
|
||||||
(1, -2, 3)
|
(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
|
assert a >= 0 and b >= 0
|
||||||
|
|
|
@ -17,26 +17,50 @@ Created by TrapinchO
|
||||||
|
|
||||||
# used alphabet --------------------------
|
# used alphabet --------------------------
|
||||||
# from string.ascii_uppercase
|
# from string.ascii_uppercase
|
||||||
abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
|
|
||||||
# -------------------------- default selection --------------------------
|
# -------------------------- default selection --------------------------
|
||||||
# rotors --------------------------
|
# rotors --------------------------
|
||||||
rotor1 = 'EGZWVONAHDCLFQMSIPJBYUKXTR'
|
rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR"
|
||||||
rotor2 = 'FOBHMDKEXQNRAULPGSJVTYICZW'
|
rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW"
|
||||||
rotor3 = 'ZJXESIUQLHAVRMDOYGTNFWPBKC'
|
rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC"
|
||||||
# reflector --------------------------
|
# reflector --------------------------
|
||||||
reflector = {'A': 'N', 'N': 'A', 'B': 'O', 'O': 'B', 'C': 'P', 'P': 'C', 'D': 'Q',
|
reflector = {
|
||||||
'Q': 'D', 'E': 'R', 'R': 'E', 'F': 'S', 'S': 'F', 'G': 'T', 'T': 'G',
|
"A": "N",
|
||||||
'H': 'U', 'U': 'H', 'I': 'V', 'V': 'I', 'J': 'W', 'W': 'J', 'K': 'X',
|
"N": "A",
|
||||||
'X': 'K', 'L': 'Y', 'Y': 'L', 'M': 'Z', 'Z': 'M'}
|
"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 --------------------------
|
# -------------------------- extra rotors --------------------------
|
||||||
rotor4 = 'RMDJXFUWGISLHVTCQNKYPBEZOA'
|
rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA"
|
||||||
rotor5 = 'SGLCPQWZHKXAREONTFBVIYJUDM'
|
rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM"
|
||||||
rotor6 = 'HVSICLTYKQUBXDWAJZOMFGPREN'
|
rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN"
|
||||||
rotor7 = 'RZWQHFMVDBKICJLNTUXAGYPSOE'
|
rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE"
|
||||||
rotor8 = 'LFKIJODBEGAMQPXVUHYSTCZRWN'
|
rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN"
|
||||||
rotor9 = 'KOAEGVDHXPQZMLFTYWJNBRCIUS'
|
rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS"
|
||||||
|
|
||||||
|
|
||||||
def _validator(rotpos: tuple, rotsel: tuple, pb: str) -> tuple:
|
def _validator(rotpos: tuple, rotsel: tuple, pb: str) -> tuple:
|
||||||
|
@ -57,19 +81,22 @@ def _validator(rotpos: tuple, rotsel: tuple, pb: str) -> tuple:
|
||||||
|
|
||||||
unique_rotsel = len(set(rotsel))
|
unique_rotsel = len(set(rotsel))
|
||||||
if unique_rotsel < 3:
|
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
|
# Checks if rotor positions are valid
|
||||||
rotorpos1, rotorpos2, rotorpos3 = rotpos
|
rotorpos1, rotorpos2, rotorpos3 = rotpos
|
||||||
if not 0 < rotorpos1 <= len(abc):
|
if not 0 < rotorpos1 <= len(abc):
|
||||||
raise ValueError(f'First rotor position is not within range of 1..26 ('
|
raise ValueError(
|
||||||
f'{rotorpos1}')
|
f"First rotor position is not within range of 1..26 (" f"{rotorpos1}"
|
||||||
|
)
|
||||||
if not 0 < rotorpos2 <= len(abc):
|
if not 0 < rotorpos2 <= len(abc):
|
||||||
raise ValueError(f'Second rotor position is not within range of 1..26 ('
|
raise ValueError(
|
||||||
f'{rotorpos2})')
|
f"Second rotor position is not within range of 1..26 (" f"{rotorpos2})"
|
||||||
|
)
|
||||||
if not 0 < rotorpos3 <= len(abc):
|
if not 0 < rotorpos3 <= len(abc):
|
||||||
raise ValueError(f'Third rotor position is not within range of 1..26 ('
|
raise ValueError(
|
||||||
f'{rotorpos3})')
|
f"Third rotor position is not within range of 1..26 (" f"{rotorpos3})"
|
||||||
|
)
|
||||||
|
|
||||||
# Validates string and returns dict
|
# Validates string and returns dict
|
||||||
pb = _plugboard(pb)
|
pb = _plugboard(pb)
|
||||||
|
@ -97,21 +124,21 @@ def _plugboard(pbstring: str) -> dict:
|
||||||
# a) is type string
|
# a) is type string
|
||||||
# b) has even length (so pairs can be made)
|
# b) has even length (so pairs can be made)
|
||||||
if not isinstance(pbstring, str):
|
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:
|
elif len(pbstring) % 2 != 0:
|
||||||
raise Exception(f'Odd number of symbols ({len(pbstring)})')
|
raise Exception(f"Odd number of symbols ({len(pbstring)})")
|
||||||
elif pbstring == '':
|
elif pbstring == "":
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
pbstring.replace(' ', '')
|
pbstring.replace(" ", "")
|
||||||
|
|
||||||
# Checks if all characters are unique
|
# Checks if all characters are unique
|
||||||
tmppbl = set()
|
tmppbl = set()
|
||||||
for i in pbstring:
|
for i in pbstring:
|
||||||
if i not in abc:
|
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:
|
elif i in tmppbl:
|
||||||
raise Exception(f'Duplicate symbol ({i})')
|
raise Exception(f"Duplicate symbol ({i})")
|
||||||
else:
|
else:
|
||||||
tmppbl.add(i)
|
tmppbl.add(i)
|
||||||
del tmppbl
|
del tmppbl
|
||||||
|
@ -125,8 +152,12 @@ def _plugboard(pbstring: str) -> dict:
|
||||||
return pb
|
return pb
|
||||||
|
|
||||||
|
|
||||||
def enigma(text: str, rotor_position: tuple,
|
def enigma(
|
||||||
rotor_selection: tuple = (rotor1, rotor2, rotor3), plugb: str = '') -> str:
|
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.
|
The only difference with real-world enigma is that I allowed string input.
|
||||||
All characters are converted to uppercase. (non-letter symbol are ignored)
|
All characters are converted to uppercase. (non-letter symbol are ignored)
|
||||||
|
@ -179,7 +210,8 @@ def enigma(text: str, rotor_position: tuple,
|
||||||
|
|
||||||
text = text.upper()
|
text = text.upper()
|
||||||
rotor_position, rotor_selection, plugboard = _validator(
|
rotor_position, rotor_selection, plugboard = _validator(
|
||||||
rotor_position, rotor_selection, plugb.upper())
|
rotor_position, rotor_selection, plugb.upper()
|
||||||
|
)
|
||||||
|
|
||||||
rotorpos1, rotorpos2, rotorpos3 = rotor_position
|
rotorpos1, rotorpos2, rotorpos3 = rotor_position
|
||||||
rotor1, rotor2, rotor3 = rotor_selection
|
rotor1, rotor2, rotor3 = rotor_selection
|
||||||
|
@ -245,12 +277,12 @@ def enigma(text: str, rotor_position: tuple,
|
||||||
return "".join(result)
|
return "".join(result)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
message = 'This is my Python script that emulates the Enigma machine from WWII.'
|
message = "This is my Python script that emulates the Enigma machine from WWII."
|
||||||
rotor_pos = (1, 1, 1)
|
rotor_pos = (1, 1, 1)
|
||||||
pb = 'pictures'
|
pb = "pictures"
|
||||||
rotor_sel = (rotor2, rotor4, rotor8)
|
rotor_sel = (rotor2, rotor4, rotor8)
|
||||||
en = enigma(message, rotor_pos, rotor_sel, pb)
|
en = enigma(message, rotor_pos, rotor_sel, pb)
|
||||||
|
|
||||||
print('Encrypted message:', en)
|
print("Encrypted message:", en)
|
||||||
print('Decrypted message:', enigma(en, rotor_pos, rotor_sel, pb))
|
print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
|
||||||
|
|
|
@ -21,20 +21,20 @@
|
||||||
class XORCipher:
|
class XORCipher:
|
||||||
def __init__(self, key=0):
|
def __init__(self, key=0):
|
||||||
"""
|
"""
|
||||||
simple constructor that receives a key or uses
|
simple constructor that receives a key or uses
|
||||||
default key = 0
|
default key = 0
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# private field
|
# private field
|
||||||
self.__key = key
|
self.__key = key
|
||||||
|
|
||||||
def encrypt(self, content, key):
|
def encrypt(self, content, key):
|
||||||
"""
|
"""
|
||||||
input: 'content' of type string and 'key' of type int
|
input: 'content' of type string and 'key' of type int
|
||||||
output: encrypted string 'content' as a list of chars
|
output: encrypted string 'content' as a list of chars
|
||||||
if key not passed the method uses the key by the constructor.
|
if key not passed the method uses the key by the constructor.
|
||||||
otherwise key = 1
|
otherwise key = 1
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
assert isinstance(key, int) and isinstance(content, str)
|
assert isinstance(key, int) and isinstance(content, str)
|
||||||
|
@ -55,11 +55,11 @@ class XORCipher:
|
||||||
|
|
||||||
def decrypt(self, content, key):
|
def decrypt(self, content, key):
|
||||||
"""
|
"""
|
||||||
input: 'content' of type list and 'key' of type int
|
input: 'content' of type list and 'key' of type int
|
||||||
output: decrypted string 'content' as a list of chars
|
output: decrypted string 'content' as a list of chars
|
||||||
if key not passed the method uses the key by the constructor.
|
if key not passed the method uses the key by the constructor.
|
||||||
otherwise key = 1
|
otherwise key = 1
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
assert isinstance(key, int) and isinstance(content, list)
|
assert isinstance(key, int) and isinstance(content, list)
|
||||||
|
@ -80,11 +80,11 @@ class XORCipher:
|
||||||
|
|
||||||
def encrypt_string(self, content, key=0):
|
def encrypt_string(self, content, key=0):
|
||||||
"""
|
"""
|
||||||
input: 'content' of type string and 'key' of type int
|
input: 'content' of type string and 'key' of type int
|
||||||
output: encrypted string 'content'
|
output: encrypted string 'content'
|
||||||
if key not passed the method uses the key by the constructor.
|
if key not passed the method uses the key by the constructor.
|
||||||
otherwise key = 1
|
otherwise key = 1
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
assert isinstance(key, int) and isinstance(content, str)
|
assert isinstance(key, int) and isinstance(content, str)
|
||||||
|
@ -105,11 +105,11 @@ class XORCipher:
|
||||||
|
|
||||||
def decrypt_string(self, content, key=0):
|
def decrypt_string(self, content, key=0):
|
||||||
"""
|
"""
|
||||||
input: 'content' of type string and 'key' of type int
|
input: 'content' of type string and 'key' of type int
|
||||||
output: decrypted string 'content'
|
output: decrypted string 'content'
|
||||||
if key not passed the method uses the key by the constructor.
|
if key not passed the method uses the key by the constructor.
|
||||||
otherwise key = 1
|
otherwise key = 1
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
assert isinstance(key, int) and isinstance(content, str)
|
assert isinstance(key, int) and isinstance(content, str)
|
||||||
|
@ -130,12 +130,12 @@ class XORCipher:
|
||||||
|
|
||||||
def encrypt_file(self, file, key=0):
|
def encrypt_file(self, file, key=0):
|
||||||
"""
|
"""
|
||||||
input: filename (str) and a key (int)
|
input: filename (str) and a key (int)
|
||||||
output: returns true if encrypt process was
|
output: returns true if encrypt process was
|
||||||
successful otherwise false
|
successful otherwise false
|
||||||
if key not passed the method uses the key by the constructor.
|
if key not passed the method uses the key by the constructor.
|
||||||
otherwise key = 1
|
otherwise key = 1
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
assert isinstance(file, str) and isinstance(key, int)
|
assert isinstance(file, str) and isinstance(key, int)
|
||||||
|
@ -155,12 +155,12 @@ class XORCipher:
|
||||||
|
|
||||||
def decrypt_file(self, file, key):
|
def decrypt_file(self, file, key):
|
||||||
"""
|
"""
|
||||||
input: filename (str) and a key (int)
|
input: filename (str) and a key (int)
|
||||||
output: returns true if decrypt process was
|
output: returns true if decrypt process was
|
||||||
successful otherwise false
|
successful otherwise false
|
||||||
if key not passed the method uses the key by the constructor.
|
if key not passed the method uses the key by the constructor.
|
||||||
otherwise key = 1
|
otherwise key = 1
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
assert isinstance(file, str) and isinstance(key, int)
|
assert isinstance(file, str) and isinstance(key, int)
|
||||||
|
|
|
@ -3,55 +3,55 @@
|
||||||
|
|
||||||
def decimal_to_any(num: int, base: int) -> str:
|
def decimal_to_any(num: int, base: int) -> str:
|
||||||
"""
|
"""
|
||||||
Convert a positive integer to another base as str.
|
Convert a positive integer to another base as str.
|
||||||
>>> decimal_to_any(0, 2)
|
>>> decimal_to_any(0, 2)
|
||||||
'0'
|
'0'
|
||||||
>>> decimal_to_any(5, 4)
|
>>> decimal_to_any(5, 4)
|
||||||
'11'
|
'11'
|
||||||
>>> decimal_to_any(20, 3)
|
>>> decimal_to_any(20, 3)
|
||||||
'202'
|
'202'
|
||||||
>>> decimal_to_any(58, 16)
|
>>> decimal_to_any(58, 16)
|
||||||
'3A'
|
'3A'
|
||||||
>>> decimal_to_any(243, 17)
|
>>> decimal_to_any(243, 17)
|
||||||
'E5'
|
'E5'
|
||||||
>>> decimal_to_any(34923, 36)
|
>>> decimal_to_any(34923, 36)
|
||||||
'QY3'
|
'QY3'
|
||||||
>>> decimal_to_any(10, 11)
|
>>> decimal_to_any(10, 11)
|
||||||
'A'
|
'A'
|
||||||
>>> decimal_to_any(16, 16)
|
>>> decimal_to_any(16, 16)
|
||||||
'10'
|
'10'
|
||||||
>>> decimal_to_any(36, 36)
|
>>> decimal_to_any(36, 36)
|
||||||
'10'
|
'10'
|
||||||
>>> # negatives will error
|
>>> # negatives will error
|
||||||
>>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS
|
>>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
ValueError: parameter must be positive int
|
ValueError: parameter must be positive int
|
||||||
>>> # floats will error
|
>>> # floats will error
|
||||||
>>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS
|
>>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
TypeError: int() can't convert non-string with explicit base
|
TypeError: int() can't convert non-string with explicit base
|
||||||
>>> # a float base will error
|
>>> # a float base will error
|
||||||
>>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS
|
>>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
TypeError: 'float' object cannot be interpreted as an integer
|
TypeError: 'float' object cannot be interpreted as an integer
|
||||||
>>> # a str base will error
|
>>> # a str base will error
|
||||||
>>> decimal_to_any(10, '16') # doctest: +ELLIPSIS
|
>>> decimal_to_any(10, '16') # doctest: +ELLIPSIS
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
TypeError: 'str' object cannot be interpreted as an integer
|
TypeError: 'str' object cannot be interpreted as an integer
|
||||||
>>> # a base less than 2 will error
|
>>> # a base less than 2 will error
|
||||||
>>> decimal_to_any(7, 0) # doctest: +ELLIPSIS
|
>>> decimal_to_any(7, 0) # doctest: +ELLIPSIS
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
ValueError: base must be >= 2
|
ValueError: base must be >= 2
|
||||||
>>> # a base greater than 36 will error
|
>>> # a base greater than 36 will error
|
||||||
>>> decimal_to_any(34, 37) # doctest: +ELLIPSIS
|
>>> decimal_to_any(34, 37) # doctest: +ELLIPSIS
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
ValueError: base must be <= 36
|
ValueError: base must be <= 36
|
||||||
"""
|
"""
|
||||||
if isinstance(num, float):
|
if isinstance(num, float):
|
||||||
raise TypeError("int() can't convert non-string with explicit base")
|
raise TypeError("int() can't convert non-string with explicit base")
|
||||||
|
|
|
@ -4,28 +4,28 @@
|
||||||
def decimal_to_binary(num: int) -> str:
|
def decimal_to_binary(num: int) -> str:
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Convert an Integer Decimal Number to a Binary Number as str.
|
Convert an Integer Decimal Number to a Binary Number as str.
|
||||||
>>> decimal_to_binary(0)
|
>>> decimal_to_binary(0)
|
||||||
'0b0'
|
'0b0'
|
||||||
>>> decimal_to_binary(2)
|
>>> decimal_to_binary(2)
|
||||||
'0b10'
|
'0b10'
|
||||||
>>> decimal_to_binary(7)
|
>>> decimal_to_binary(7)
|
||||||
'0b111'
|
'0b111'
|
||||||
>>> decimal_to_binary(35)
|
>>> decimal_to_binary(35)
|
||||||
'0b100011'
|
'0b100011'
|
||||||
>>> # negatives work too
|
>>> # negatives work too
|
||||||
>>> decimal_to_binary(-2)
|
>>> decimal_to_binary(-2)
|
||||||
'-0b10'
|
'-0b10'
|
||||||
>>> # other floats will error
|
>>> # other floats will error
|
||||||
>>> decimal_to_binary(16.16) # doctest: +ELLIPSIS
|
>>> decimal_to_binary(16.16) # doctest: +ELLIPSIS
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
TypeError: 'float' object cannot be interpreted as an integer
|
TypeError: 'float' object cannot be interpreted as an integer
|
||||||
>>> # strings will error as well
|
>>> # strings will error as well
|
||||||
>>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS
|
>>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
TypeError: 'str' object cannot be interpreted as an integer
|
TypeError: 'str' object cannot be interpreted as an integer
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if type(num) == float:
|
if type(num) == float:
|
||||||
|
|
|
@ -23,39 +23,39 @@ values = {
|
||||||
|
|
||||||
def decimal_to_hexadecimal(decimal):
|
def decimal_to_hexadecimal(decimal):
|
||||||
"""
|
"""
|
||||||
take integer decimal value, return hexadecimal representation as str beginning
|
take integer decimal value, return hexadecimal representation as str beginning
|
||||||
with 0x
|
with 0x
|
||||||
>>> decimal_to_hexadecimal(5)
|
>>> decimal_to_hexadecimal(5)
|
||||||
'0x5'
|
'0x5'
|
||||||
>>> decimal_to_hexadecimal(15)
|
>>> decimal_to_hexadecimal(15)
|
||||||
'0xf'
|
'0xf'
|
||||||
>>> decimal_to_hexadecimal(37)
|
>>> decimal_to_hexadecimal(37)
|
||||||
'0x25'
|
'0x25'
|
||||||
>>> decimal_to_hexadecimal(255)
|
>>> decimal_to_hexadecimal(255)
|
||||||
'0xff'
|
'0xff'
|
||||||
>>> decimal_to_hexadecimal(4096)
|
>>> decimal_to_hexadecimal(4096)
|
||||||
'0x1000'
|
'0x1000'
|
||||||
>>> decimal_to_hexadecimal(999098)
|
>>> decimal_to_hexadecimal(999098)
|
||||||
'0xf3eba'
|
'0xf3eba'
|
||||||
>>> # negatives work too
|
>>> # negatives work too
|
||||||
>>> decimal_to_hexadecimal(-256)
|
>>> decimal_to_hexadecimal(-256)
|
||||||
'-0x100'
|
'-0x100'
|
||||||
>>> # floats are acceptable if equivalent to an int
|
>>> # floats are acceptable if equivalent to an int
|
||||||
>>> decimal_to_hexadecimal(17.0)
|
>>> decimal_to_hexadecimal(17.0)
|
||||||
'0x11'
|
'0x11'
|
||||||
>>> # other floats will error
|
>>> # other floats will error
|
||||||
>>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS
|
>>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
AssertionError
|
AssertionError
|
||||||
>>> # strings will error as well
|
>>> # strings will error as well
|
||||||
>>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS
|
>>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
AssertionError
|
AssertionError
|
||||||
>>> # results are the same when compared to Python's default hex function
|
>>> # results are the same when compared to Python's default hex function
|
||||||
>>> decimal_to_hexadecimal(-256) == hex(-256)
|
>>> decimal_to_hexadecimal(-256) == hex(-256)
|
||||||
True
|
True
|
||||||
"""
|
"""
|
||||||
assert type(decimal) in (int, float) and decimal == int(decimal)
|
assert type(decimal) in (int, float) and decimal == int(decimal)
|
||||||
hexadecimal = ""
|
hexadecimal = ""
|
||||||
|
|
|
@ -109,7 +109,7 @@ def right_rotation(node):
|
||||||
|
|
||||||
def left_rotation(node):
|
def left_rotation(node):
|
||||||
"""
|
"""
|
||||||
a mirror symmetry rotation of the left_rotation
|
a mirror symmetry rotation of the left_rotation
|
||||||
"""
|
"""
|
||||||
print("right rotation node:", node.get_data())
|
print("right rotation node:", node.get_data())
|
||||||
ret = node.get_right()
|
ret = node.get_right()
|
||||||
|
|
|
@ -28,11 +28,11 @@ class RedBlackTree:
|
||||||
right: Optional["RedBlackTree"] = None,
|
right: Optional["RedBlackTree"] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Initialize a new Red-Black Tree node with the given values:
|
"""Initialize a new Red-Black Tree node with the given values:
|
||||||
label: The value associated with this node
|
label: The value associated with this node
|
||||||
color: 0 if black, 1 if red
|
color: 0 if black, 1 if red
|
||||||
parent: The parent to this node
|
parent: The parent to this node
|
||||||
left: This node's left child
|
left: This node's left child
|
||||||
right: This node's right child
|
right: This node's right child
|
||||||
"""
|
"""
|
||||||
self.label = label
|
self.label = label
|
||||||
self.parent = parent
|
self.parent = parent
|
||||||
|
|
|
@ -118,7 +118,7 @@ def inorder(root: Node):
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
inorder(root.left)
|
inorder(root.left)
|
||||||
print(root.value, end=" ")
|
print(root.value, end=",")
|
||||||
inorder(root.right)
|
inorder(root.right)
|
||||||
|
|
||||||
|
|
||||||
|
@ -130,19 +130,19 @@ def interactTreap(root, args):
|
||||||
|
|
||||||
>>> root = interactTreap(None, "+1")
|
>>> root = interactTreap(None, "+1")
|
||||||
>>> inorder(root)
|
>>> inorder(root)
|
||||||
1
|
1,
|
||||||
>>> root = interactTreap(root, "+3 +5 +17 +19 +2 +16 +4 +0")
|
>>> root = interactTreap(root, "+3 +5 +17 +19 +2 +16 +4 +0")
|
||||||
>>> inorder(root)
|
>>> inorder(root)
|
||||||
0 1 2 3 4 5 16 17 19
|
0,1,2,3,4,5,16,17,19,
|
||||||
>>> root = interactTreap(root, "+4 +4 +4")
|
>>> root = interactTreap(root, "+4 +4 +4")
|
||||||
>>> inorder(root)
|
>>> inorder(root)
|
||||||
0 1 2 3 4 4 4 4 5 16 17 19
|
0,1,2,3,4,4,4,4,5,16,17,19,
|
||||||
>>> root = interactTreap(root, "-0")
|
>>> root = interactTreap(root, "-0")
|
||||||
>>> inorder(root)
|
>>> inorder(root)
|
||||||
1 2 3 4 4 4 4 5 16 17 19
|
1,2,3,4,4,4,4,5,16,17,19,
|
||||||
>>> root = interactTreap(root, "-4")
|
>>> root = interactTreap(root, "-4")
|
||||||
>>> inorder(root)
|
>>> inorder(root)
|
||||||
1 2 3 5 16 17 19
|
1,2,3,5,16,17,19,
|
||||||
>>> root = interactTreap(root, "=0")
|
>>> root = interactTreap(root, "=0")
|
||||||
Unknown command
|
Unknown command
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -5,7 +5,7 @@ from number_theory.prime_numbers import check_prime, next_prime
|
||||||
|
|
||||||
class DoubleHash(HashTable):
|
class DoubleHash(HashTable):
|
||||||
"""
|
"""
|
||||||
Hash Table example with open addressing and Double Hash
|
Hash Table example with open addressing and Double Hash
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
|
|
|
@ -4,7 +4,7 @@ from number_theory.prime_numbers import next_prime
|
||||||
|
|
||||||
class HashTable:
|
class HashTable:
|
||||||
"""
|
"""
|
||||||
Basic Hash Table example with open addressing and linear probing
|
Basic Hash Table example with open addressing and linear probing
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, size_table, charge_factor=None, lim_charge=None):
|
def __init__(self, size_table, charge_factor=None, lim_charge=None):
|
||||||
|
|
|
@ -6,8 +6,8 @@
|
||||||
|
|
||||||
def check_prime(number):
|
def check_prime(number):
|
||||||
"""
|
"""
|
||||||
it's not the best solution
|
it's not the best solution
|
||||||
"""
|
"""
|
||||||
special_non_primes = [0, 1, 2]
|
special_non_primes = [0, 1, 2]
|
||||||
if number in special_non_primes[:2]:
|
if number in special_non_primes[:2]:
|
||||||
return 2
|
return 2
|
||||||
|
|
|
@ -5,7 +5,7 @@ from hash_table import HashTable
|
||||||
|
|
||||||
class QuadraticProbing(HashTable):
|
class QuadraticProbing(HashTable):
|
||||||
"""
|
"""
|
||||||
Basic Hash Table example with open addressing using Quadratic Probing
|
Basic Hash Table example with open addressing using Quadratic Probing
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
|
|
|
@ -61,7 +61,7 @@ class _DoublyLinkedBase:
|
||||||
|
|
||||||
class LinkedDeque(_DoublyLinkedBase):
|
class LinkedDeque(_DoublyLinkedBase):
|
||||||
def first(self):
|
def first(self):
|
||||||
""" return first element
|
"""return first element
|
||||||
>>> d = LinkedDeque()
|
>>> d = LinkedDeque()
|
||||||
>>> d.add_first('A').first()
|
>>> d.add_first('A').first()
|
||||||
'A'
|
'A'
|
||||||
|
@ -73,7 +73,7 @@ class LinkedDeque(_DoublyLinkedBase):
|
||||||
return self._header._next._data
|
return self._header._next._data
|
||||||
|
|
||||||
def last(self):
|
def last(self):
|
||||||
""" return last element
|
"""return last element
|
||||||
>>> d = LinkedDeque()
|
>>> d = LinkedDeque()
|
||||||
>>> d.add_last('A').last()
|
>>> d.add_last('A').last()
|
||||||
'A'
|
'A'
|
||||||
|
@ -87,14 +87,14 @@ class LinkedDeque(_DoublyLinkedBase):
|
||||||
# DEque Insert Operations (At the front, At the end)
|
# DEque Insert Operations (At the front, At the end)
|
||||||
|
|
||||||
def add_first(self, element):
|
def add_first(self, element):
|
||||||
""" insertion in the front
|
"""insertion in the front
|
||||||
>>> LinkedDeque().add_first('AV').first()
|
>>> LinkedDeque().add_first('AV').first()
|
||||||
'AV'
|
'AV'
|
||||||
"""
|
"""
|
||||||
return self._insert(self._header, element, self._header._next)
|
return self._insert(self._header, element, self._header._next)
|
||||||
|
|
||||||
def add_last(self, element):
|
def add_last(self, element):
|
||||||
""" insertion in the end
|
"""insertion in the end
|
||||||
>>> LinkedDeque().add_last('B').last()
|
>>> LinkedDeque().add_last('B').last()
|
||||||
'B'
|
'B'
|
||||||
"""
|
"""
|
||||||
|
@ -103,7 +103,7 @@ class LinkedDeque(_DoublyLinkedBase):
|
||||||
# DEqueu Remove Operations (At the front, At the end)
|
# DEqueu Remove Operations (At the front, At the end)
|
||||||
|
|
||||||
def remove_first(self):
|
def remove_first(self):
|
||||||
""" removal from the front
|
"""removal from the front
|
||||||
>>> d = LinkedDeque()
|
>>> d = LinkedDeque()
|
||||||
>>> d.is_empty()
|
>>> d.is_empty()
|
||||||
True
|
True
|
||||||
|
@ -123,7 +123,7 @@ class LinkedDeque(_DoublyLinkedBase):
|
||||||
return self._delete(self._header._next)
|
return self._delete(self._header._next)
|
||||||
|
|
||||||
def remove_last(self):
|
def remove_last(self):
|
||||||
""" removal in the end
|
"""removal in the end
|
||||||
>>> d = LinkedDeque()
|
>>> d = LinkedDeque()
|
||||||
>>> d.is_empty()
|
>>> d.is_empty()
|
||||||
True
|
True
|
||||||
|
|
|
@ -10,7 +10,7 @@ def is_operand(char):
|
||||||
|
|
||||||
|
|
||||||
def precedence(char):
|
def precedence(char):
|
||||||
""" Return integer value representing an operator's precedence, or
|
"""Return integer value representing an operator's precedence, or
|
||||||
order of operation.
|
order of operation.
|
||||||
|
|
||||||
https://en.wikipedia.org/wiki/Order_of_operations
|
https://en.wikipedia.org/wiki/Order_of_operations
|
||||||
|
@ -20,7 +20,7 @@ def precedence(char):
|
||||||
|
|
||||||
|
|
||||||
def infix_to_postfix(expression):
|
def infix_to_postfix(expression):
|
||||||
""" Convert infix notation to postfix notation using the Shunting-yard
|
"""Convert infix notation to postfix notation using the Shunting-yard
|
||||||
algorithm.
|
algorithm.
|
||||||
|
|
||||||
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
|
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
|
||||||
|
|
|
@ -2,7 +2,7 @@ __author__ = "Omkar Pathak"
|
||||||
|
|
||||||
|
|
||||||
class Stack:
|
class Stack:
|
||||||
""" A stack is an abstract data type that serves as a collection of
|
"""A stack is an abstract data type that serves as a collection of
|
||||||
elements with two principal operations: push() and pop(). push() adds an
|
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
|
element to the top of the stack, and pop() removes an element from the top
|
||||||
of a stack. The order in which elements come off of a stack are
|
of a stack. The order in which elements come off of a stack are
|
||||||
|
|
|
@ -10,98 +10,98 @@ import numpy as np
|
||||||
# Class implemented to calculus the index
|
# Class implemented to calculus the index
|
||||||
class IndexCalculation:
|
class IndexCalculation:
|
||||||
"""
|
"""
|
||||||
# Class Summary
|
# Class Summary
|
||||||
This algorithm consists in calculating vegetation indices, these
|
This algorithm consists in calculating vegetation indices, these
|
||||||
indices can be used for precision agriculture for example (or remote
|
indices can be used for precision agriculture for example (or remote
|
||||||
sensing). There are functions to define the data and to calculate the
|
sensing). There are functions to define the data and to calculate the
|
||||||
implemented indices.
|
implemented indices.
|
||||||
|
|
||||||
# Vegetation index
|
# Vegetation index
|
||||||
https://en.wikipedia.org/wiki/Vegetation_Index
|
https://en.wikipedia.org/wiki/Vegetation_Index
|
||||||
A Vegetation Index (VI) is a spectral transformation of two or more bands
|
A Vegetation Index (VI) is a spectral transformation of two or more bands
|
||||||
designed to enhance the contribution of vegetation properties and allow
|
designed to enhance the contribution of vegetation properties and allow
|
||||||
reliable spatial and temporal inter-comparisons of terrestrial
|
reliable spatial and temporal inter-comparisons of terrestrial
|
||||||
photosynthetic activity and canopy structural variations
|
photosynthetic activity and canopy structural variations
|
||||||
|
|
||||||
# Information about channels (Wavelength range for each)
|
# Information about channels (Wavelength range for each)
|
||||||
* nir - near-infrared
|
* nir - near-infrared
|
||||||
https://www.malvernpanalytical.com/br/products/technology/near-infrared-spectroscopy
|
https://www.malvernpanalytical.com/br/products/technology/near-infrared-spectroscopy
|
||||||
Wavelength Range 700 nm to 2500 nm
|
Wavelength Range 700 nm to 2500 nm
|
||||||
* Red Edge
|
* Red Edge
|
||||||
https://en.wikipedia.org/wiki/Red_edge
|
https://en.wikipedia.org/wiki/Red_edge
|
||||||
Wavelength Range 680 nm to 730 nm
|
Wavelength Range 680 nm to 730 nm
|
||||||
* red
|
* red
|
||||||
https://en.wikipedia.org/wiki/Color
|
https://en.wikipedia.org/wiki/Color
|
||||||
Wavelength Range 635 nm to 700 nm
|
Wavelength Range 635 nm to 700 nm
|
||||||
* blue
|
* blue
|
||||||
https://en.wikipedia.org/wiki/Color
|
https://en.wikipedia.org/wiki/Color
|
||||||
Wavelength Range 450 nm to 490 nm
|
Wavelength Range 450 nm to 490 nm
|
||||||
* green
|
* green
|
||||||
https://en.wikipedia.org/wiki/Color
|
https://en.wikipedia.org/wiki/Color
|
||||||
Wavelength Range 520 nm to 560 nm
|
Wavelength Range 520 nm to 560 nm
|
||||||
|
|
||||||
|
|
||||||
# Implemented index list
|
# Implemented index list
|
||||||
#"abbreviationOfIndexName" -- list of channels used
|
#"abbreviationOfIndexName" -- list of channels used
|
||||||
|
|
||||||
#"ARVI2" -- red, nir
|
#"ARVI2" -- red, nir
|
||||||
#"CCCI" -- red, redEdge, nir
|
#"CCCI" -- red, redEdge, nir
|
||||||
#"CVI" -- red, green, nir
|
#"CVI" -- red, green, nir
|
||||||
#"GLI" -- red, green, blue
|
#"GLI" -- red, green, blue
|
||||||
#"NDVI" -- red, nir
|
#"NDVI" -- red, nir
|
||||||
#"BNDVI" -- blue, nir
|
#"BNDVI" -- blue, nir
|
||||||
#"redEdgeNDVI" -- red, redEdge
|
#"redEdgeNDVI" -- red, redEdge
|
||||||
#"GNDVI" -- green, nir
|
#"GNDVI" -- green, nir
|
||||||
#"GBNDVI" -- green, blue, nir
|
#"GBNDVI" -- green, blue, nir
|
||||||
#"GRNDVI" -- red, green, nir
|
#"GRNDVI" -- red, green, nir
|
||||||
#"RBNDVI" -- red, blue, nir
|
#"RBNDVI" -- red, blue, nir
|
||||||
#"PNDVI" -- red, green, blue, nir
|
#"PNDVI" -- red, green, blue, nir
|
||||||
#"ATSAVI" -- red, nir
|
#"ATSAVI" -- red, nir
|
||||||
#"BWDRVI" -- blue, nir
|
#"BWDRVI" -- blue, nir
|
||||||
#"CIgreen" -- green, nir
|
#"CIgreen" -- green, nir
|
||||||
#"CIrededge" -- redEdge, nir
|
#"CIrededge" -- redEdge, nir
|
||||||
#"CI" -- red, blue
|
#"CI" -- red, blue
|
||||||
#"CTVI" -- red, nir
|
#"CTVI" -- red, nir
|
||||||
#"GDVI" -- green, nir
|
#"GDVI" -- green, nir
|
||||||
#"EVI" -- red, blue, nir
|
#"EVI" -- red, blue, nir
|
||||||
#"GEMI" -- red, nir
|
#"GEMI" -- red, nir
|
||||||
#"GOSAVI" -- green, nir
|
#"GOSAVI" -- green, nir
|
||||||
#"GSAVI" -- green, nir
|
#"GSAVI" -- green, nir
|
||||||
#"Hue" -- red, green, blue
|
#"Hue" -- red, green, blue
|
||||||
#"IVI" -- red, nir
|
#"IVI" -- red, nir
|
||||||
#"IPVI" -- red, nir
|
#"IPVI" -- red, nir
|
||||||
#"I" -- red, green, blue
|
#"I" -- red, green, blue
|
||||||
#"RVI" -- red, nir
|
#"RVI" -- red, nir
|
||||||
#"MRVI" -- red, nir
|
#"MRVI" -- red, nir
|
||||||
#"MSAVI" -- red, nir
|
#"MSAVI" -- red, nir
|
||||||
#"NormG" -- red, green, nir
|
#"NormG" -- red, green, nir
|
||||||
#"NormNIR" -- red, green, nir
|
#"NormNIR" -- red, green, nir
|
||||||
#"NormR" -- red, green, nir
|
#"NormR" -- red, green, nir
|
||||||
#"NGRDI" -- red, green
|
#"NGRDI" -- red, green
|
||||||
#"RI" -- red, green
|
#"RI" -- red, green
|
||||||
#"S" -- red, green, blue
|
#"S" -- red, green, blue
|
||||||
#"IF" -- red, green, blue
|
#"IF" -- red, green, blue
|
||||||
#"DVI" -- red, nir
|
#"DVI" -- red, nir
|
||||||
#"TVI" -- red, nir
|
#"TVI" -- red, nir
|
||||||
#"NDRE" -- redEdge, nir
|
#"NDRE" -- redEdge, nir
|
||||||
|
|
||||||
#list of all index implemented
|
#list of all index implemented
|
||||||
#allIndex = ["ARVI2", "CCCI", "CVI", "GLI", "NDVI", "BNDVI", "redEdgeNDVI",
|
#allIndex = ["ARVI2", "CCCI", "CVI", "GLI", "NDVI", "BNDVI", "redEdgeNDVI",
|
||||||
"GNDVI", "GBNDVI", "GRNDVI", "RBNDVI", "PNDVI", "ATSAVI",
|
"GNDVI", "GBNDVI", "GRNDVI", "RBNDVI", "PNDVI", "ATSAVI",
|
||||||
"BWDRVI", "CIgreen", "CIrededge", "CI", "CTVI", "GDVI", "EVI",
|
"BWDRVI", "CIgreen", "CIrededge", "CI", "CTVI", "GDVI", "EVI",
|
||||||
"GEMI", "GOSAVI", "GSAVI", "Hue", "IVI", "IPVI", "I", "RVI",
|
"GEMI", "GOSAVI", "GSAVI", "Hue", "IVI", "IPVI", "I", "RVI",
|
||||||
"MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI",
|
"MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI",
|
||||||
"S", "IF", "DVI", "TVI", "NDRE"]
|
"S", "IF", "DVI", "TVI", "NDRE"]
|
||||||
|
|
||||||
#list of index with not blue channel
|
#list of index with not blue channel
|
||||||
#notBlueIndex = ["ARVI2", "CCCI", "CVI", "NDVI", "redEdgeNDVI", "GNDVI",
|
#notBlueIndex = ["ARVI2", "CCCI", "CVI", "NDVI", "redEdgeNDVI", "GNDVI",
|
||||||
"GRNDVI", "ATSAVI", "CIgreen", "CIrededge", "CTVI", "GDVI",
|
"GRNDVI", "ATSAVI", "CIgreen", "CIrededge", "CTVI", "GDVI",
|
||||||
"GEMI", "GOSAVI", "GSAVI", "IVI", "IPVI", "RVI", "MRVI",
|
"GEMI", "GOSAVI", "GSAVI", "IVI", "IPVI", "RVI", "MRVI",
|
||||||
"MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "DVI",
|
"MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "DVI",
|
||||||
"TVI", "NDRE"]
|
"TVI", "NDRE"]
|
||||||
|
|
||||||
#list of index just with RGB channels
|
#list of index just with RGB channels
|
||||||
#RGBIndex = ["GLI", "CI", "Hue", "I", "NGRDI", "RI", "S", "IF"]
|
#RGBIndex = ["GLI", "CI", "Hue", "I", "NGRDI", "RI", "S", "IF"]
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, red=None, green=None, blue=None, redEdge=None, nir=None):
|
def __init__(self, red=None, green=None, blue=None, redEdge=None, nir=None):
|
||||||
|
@ -189,9 +189,9 @@ class IndexCalculation:
|
||||||
|
|
||||||
def CCCI(self):
|
def CCCI(self):
|
||||||
"""
|
"""
|
||||||
Canopy Chlorophyll Content Index
|
Canopy Chlorophyll Content Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=224
|
https://www.indexdatabase.de/db/i-single.php?id=224
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / (
|
return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / (
|
||||||
(self.nir - self.red) / (self.nir + self.red)
|
(self.nir - self.red) / (self.nir + self.red)
|
||||||
|
@ -199,17 +199,17 @@ class IndexCalculation:
|
||||||
|
|
||||||
def CVI(self):
|
def CVI(self):
|
||||||
"""
|
"""
|
||||||
Chlorophyll vegetation index
|
Chlorophyll vegetation index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=391
|
https://www.indexdatabase.de/db/i-single.php?id=391
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return self.nir * (self.red / (self.green ** 2))
|
return self.nir * (self.red / (self.green ** 2))
|
||||||
|
|
||||||
def GLI(self):
|
def GLI(self):
|
||||||
"""
|
"""
|
||||||
self.green leaf index
|
self.green leaf index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=375
|
https://www.indexdatabase.de/db/i-single.php?id=375
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (2 * self.green - self.red - self.blue) / (
|
return (2 * self.green - self.red - self.blue) / (
|
||||||
2 * self.green + self.red + self.blue
|
2 * self.green + self.red + self.blue
|
||||||
|
@ -217,43 +217,43 @@ class IndexCalculation:
|
||||||
|
|
||||||
def NDVI(self):
|
def NDVI(self):
|
||||||
"""
|
"""
|
||||||
Normalized Difference self.nir/self.red Normalized Difference Vegetation
|
Normalized Difference self.nir/self.red Normalized Difference Vegetation
|
||||||
Index, Calibrated NDVI - CDVI
|
Index, Calibrated NDVI - CDVI
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=58
|
https://www.indexdatabase.de/db/i-single.php?id=58
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir - self.red) / (self.nir + self.red)
|
return (self.nir - self.red) / (self.nir + self.red)
|
||||||
|
|
||||||
def BNDVI(self):
|
def BNDVI(self):
|
||||||
"""
|
"""
|
||||||
Normalized Difference self.nir/self.blue self.blue-normalized difference
|
Normalized Difference self.nir/self.blue self.blue-normalized difference
|
||||||
vegetation index
|
vegetation index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=135
|
https://www.indexdatabase.de/db/i-single.php?id=135
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir - self.blue) / (self.nir + self.blue)
|
return (self.nir - self.blue) / (self.nir + self.blue)
|
||||||
|
|
||||||
def redEdgeNDVI(self):
|
def redEdgeNDVI(self):
|
||||||
"""
|
"""
|
||||||
Normalized Difference self.rededge/self.red
|
Normalized Difference self.rededge/self.red
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=235
|
https://www.indexdatabase.de/db/i-single.php?id=235
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.redEdge - self.red) / (self.redEdge + self.red)
|
return (self.redEdge - self.red) / (self.redEdge + self.red)
|
||||||
|
|
||||||
def GNDVI(self):
|
def GNDVI(self):
|
||||||
"""
|
"""
|
||||||
Normalized Difference self.nir/self.green self.green NDVI
|
Normalized Difference self.nir/self.green self.green NDVI
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=401
|
https://www.indexdatabase.de/db/i-single.php?id=401
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir - self.green) / (self.nir + self.green)
|
return (self.nir - self.green) / (self.nir + self.green)
|
||||||
|
|
||||||
def GBNDVI(self):
|
def GBNDVI(self):
|
||||||
"""
|
"""
|
||||||
self.green-self.blue NDVI
|
self.green-self.blue NDVI
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=186
|
https://www.indexdatabase.de/db/i-single.php?id=186
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir - (self.green + self.blue)) / (
|
return (self.nir - (self.green + self.blue)) / (
|
||||||
self.nir + (self.green + self.blue)
|
self.nir + (self.green + self.blue)
|
||||||
|
@ -261,9 +261,9 @@ class IndexCalculation:
|
||||||
|
|
||||||
def GRNDVI(self):
|
def GRNDVI(self):
|
||||||
"""
|
"""
|
||||||
self.green-self.red NDVI
|
self.green-self.red NDVI
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=185
|
https://www.indexdatabase.de/db/i-single.php?id=185
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir - (self.green + self.red)) / (
|
return (self.nir - (self.green + self.red)) / (
|
||||||
self.nir + (self.green + self.red)
|
self.nir + (self.green + self.red)
|
||||||
|
@ -271,17 +271,17 @@ class IndexCalculation:
|
||||||
|
|
||||||
def RBNDVI(self):
|
def RBNDVI(self):
|
||||||
"""
|
"""
|
||||||
self.red-self.blue NDVI
|
self.red-self.blue NDVI
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=187
|
https://www.indexdatabase.de/db/i-single.php?id=187
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red))
|
return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red))
|
||||||
|
|
||||||
def PNDVI(self):
|
def PNDVI(self):
|
||||||
"""
|
"""
|
||||||
Pan NDVI
|
Pan NDVI
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=188
|
https://www.indexdatabase.de/db/i-single.php?id=188
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir - (self.green + self.red + self.blue)) / (
|
return (self.nir - (self.green + self.red + self.blue)) / (
|
||||||
self.nir + (self.green + self.red + self.blue)
|
self.nir + (self.green + self.red + self.blue)
|
||||||
|
@ -289,9 +289,9 @@ class IndexCalculation:
|
||||||
|
|
||||||
def ATSAVI(self, X=0.08, a=1.22, b=0.03):
|
def ATSAVI(self, X=0.08, a=1.22, b=0.03):
|
||||||
"""
|
"""
|
||||||
Adjusted transformed soil-adjusted VI
|
Adjusted transformed soil-adjusted VI
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=209
|
https://www.indexdatabase.de/db/i-single.php?id=209
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return a * (
|
return a * (
|
||||||
(self.nir - a * self.red - b)
|
(self.nir - a * self.red - b)
|
||||||
|
@ -300,58 +300,58 @@ class IndexCalculation:
|
||||||
|
|
||||||
def BWDRVI(self):
|
def BWDRVI(self):
|
||||||
"""
|
"""
|
||||||
self.blue-wide dynamic range vegetation index
|
self.blue-wide dynamic range vegetation index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=136
|
https://www.indexdatabase.de/db/i-single.php?id=136
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue)
|
return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue)
|
||||||
|
|
||||||
def CIgreen(self):
|
def CIgreen(self):
|
||||||
"""
|
"""
|
||||||
Chlorophyll Index self.green
|
Chlorophyll Index self.green
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=128
|
https://www.indexdatabase.de/db/i-single.php?id=128
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir / self.green) - 1
|
return (self.nir / self.green) - 1
|
||||||
|
|
||||||
def CIrededge(self):
|
def CIrededge(self):
|
||||||
"""
|
"""
|
||||||
Chlorophyll Index self.redEdge
|
Chlorophyll Index self.redEdge
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=131
|
https://www.indexdatabase.de/db/i-single.php?id=131
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir / self.redEdge) - 1
|
return (self.nir / self.redEdge) - 1
|
||||||
|
|
||||||
def CI(self):
|
def CI(self):
|
||||||
"""
|
"""
|
||||||
Coloration Index
|
Coloration Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=11
|
https://www.indexdatabase.de/db/i-single.php?id=11
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.red - self.blue) / self.red
|
return (self.red - self.blue) / self.red
|
||||||
|
|
||||||
def CTVI(self):
|
def CTVI(self):
|
||||||
"""
|
"""
|
||||||
Corrected Transformed Vegetation Index
|
Corrected Transformed Vegetation Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=244
|
https://www.indexdatabase.de/db/i-single.php?id=244
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
ndvi = self.NDVI()
|
ndvi = self.NDVI()
|
||||||
return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2))
|
return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2))
|
||||||
|
|
||||||
def GDVI(self):
|
def GDVI(self):
|
||||||
"""
|
"""
|
||||||
Difference self.nir/self.green self.green Difference Vegetation Index
|
Difference self.nir/self.green self.green Difference Vegetation Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=27
|
https://www.indexdatabase.de/db/i-single.php?id=27
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return self.nir - self.green
|
return self.nir - self.green
|
||||||
|
|
||||||
def EVI(self):
|
def EVI(self):
|
||||||
"""
|
"""
|
||||||
Enhanced Vegetation Index
|
Enhanced Vegetation Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=16
|
https://www.indexdatabase.de/db/i-single.php?id=16
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return 2.5 * (
|
return 2.5 * (
|
||||||
(self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1)
|
(self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1)
|
||||||
|
@ -359,9 +359,9 @@ class IndexCalculation:
|
||||||
|
|
||||||
def GEMI(self):
|
def GEMI(self):
|
||||||
"""
|
"""
|
||||||
Global Environment Monitoring Index
|
Global Environment Monitoring Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=25
|
https://www.indexdatabase.de/db/i-single.php?id=25
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
n = (2 * (self.nir ** 2 - self.red ** 2) + 1.5 * self.nir + 0.5 * self.red) / (
|
n = (2 * (self.nir ** 2 - self.red ** 2) + 1.5 * self.nir + 0.5 * self.red) / (
|
||||||
self.nir + self.red + 0.5
|
self.nir + self.red + 0.5
|
||||||
|
@ -370,27 +370,27 @@ class IndexCalculation:
|
||||||
|
|
||||||
def GOSAVI(self, Y=0.16):
|
def GOSAVI(self, Y=0.16):
|
||||||
"""
|
"""
|
||||||
self.green Optimized Soil Adjusted Vegetation Index
|
self.green Optimized Soil Adjusted Vegetation Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=29
|
https://www.indexdatabase.de/db/i-single.php?id=29
|
||||||
mit Y = 0,16
|
mit Y = 0,16
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir - self.green) / (self.nir + self.green + Y)
|
return (self.nir - self.green) / (self.nir + self.green + Y)
|
||||||
|
|
||||||
def GSAVI(self, L=0.5):
|
def GSAVI(self, L=0.5):
|
||||||
"""
|
"""
|
||||||
self.green Soil Adjusted Vegetation Index
|
self.green Soil Adjusted Vegetation Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=31
|
https://www.indexdatabase.de/db/i-single.php?id=31
|
||||||
mit L = 0,5
|
mit L = 0,5
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return ((self.nir - self.green) / (self.nir + self.green + L)) * (1 + L)
|
return ((self.nir - self.green) / (self.nir + self.green + L)) * (1 + L)
|
||||||
|
|
||||||
def Hue(self):
|
def Hue(self):
|
||||||
"""
|
"""
|
||||||
Hue
|
Hue
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=34
|
https://www.indexdatabase.de/db/i-single.php?id=34
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return np.arctan(
|
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)
|
||||||
|
@ -398,51 +398,51 @@ class IndexCalculation:
|
||||||
|
|
||||||
def IVI(self, a=None, b=None):
|
def IVI(self, a=None, b=None):
|
||||||
"""
|
"""
|
||||||
Ideal vegetation index
|
Ideal vegetation index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=276
|
https://www.indexdatabase.de/db/i-single.php?id=276
|
||||||
b=intercept of vegetation line
|
b=intercept of vegetation line
|
||||||
a=soil line slope
|
a=soil line slope
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir - b) / (a * self.red)
|
return (self.nir - b) / (a * self.red)
|
||||||
|
|
||||||
def IPVI(self):
|
def IPVI(self):
|
||||||
"""
|
"""
|
||||||
Infraself.red percentage vegetation index
|
Infraself.red percentage vegetation index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=35
|
https://www.indexdatabase.de/db/i-single.php?id=35
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.nir / ((self.nir + self.red) / 2)) * (self.NDVI() + 1)
|
return (self.nir / ((self.nir + self.red) / 2)) * (self.NDVI() + 1)
|
||||||
|
|
||||||
def I(self): # noqa: E741,E743
|
def I(self): # noqa: E741,E743
|
||||||
"""
|
"""
|
||||||
Intensity
|
Intensity
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=36
|
https://www.indexdatabase.de/db/i-single.php?id=36
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.red + self.green + self.blue) / 30.5
|
return (self.red + self.green + self.blue) / 30.5
|
||||||
|
|
||||||
def RVI(self):
|
def RVI(self):
|
||||||
"""
|
"""
|
||||||
Ratio-Vegetation-Index
|
Ratio-Vegetation-Index
|
||||||
http://www.seos-project.eu/modules/remotesensing/remotesensing-c03-s01-p01.html
|
http://www.seos-project.eu/modules/remotesensing/remotesensing-c03-s01-p01.html
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return self.nir / self.red
|
return self.nir / self.red
|
||||||
|
|
||||||
def MRVI(self):
|
def MRVI(self):
|
||||||
"""
|
"""
|
||||||
Modified Normalized Difference Vegetation Index RVI
|
Modified Normalized Difference Vegetation Index RVI
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=275
|
https://www.indexdatabase.de/db/i-single.php?id=275
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.RVI() - 1) / (self.RVI() + 1)
|
return (self.RVI() - 1) / (self.RVI() + 1)
|
||||||
|
|
||||||
def MSAVI(self):
|
def MSAVI(self):
|
||||||
"""
|
"""
|
||||||
Modified Soil Adjusted Vegetation Index
|
Modified Soil Adjusted Vegetation Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=44
|
https://www.indexdatabase.de/db/i-single.php?id=44
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (
|
return (
|
||||||
(2 * self.nir + 1)
|
(2 * self.nir + 1)
|
||||||
|
@ -451,51 +451,51 @@ class IndexCalculation:
|
||||||
|
|
||||||
def NormG(self):
|
def NormG(self):
|
||||||
"""
|
"""
|
||||||
Norm G
|
Norm G
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=50
|
https://www.indexdatabase.de/db/i-single.php?id=50
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return self.green / (self.nir + self.red + self.green)
|
return self.green / (self.nir + self.red + self.green)
|
||||||
|
|
||||||
def NormNIR(self):
|
def NormNIR(self):
|
||||||
"""
|
"""
|
||||||
Norm self.nir
|
Norm self.nir
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=51
|
https://www.indexdatabase.de/db/i-single.php?id=51
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return self.nir / (self.nir + self.red + self.green)
|
return self.nir / (self.nir + self.red + self.green)
|
||||||
|
|
||||||
def NormR(self):
|
def NormR(self):
|
||||||
"""
|
"""
|
||||||
Norm R
|
Norm R
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=52
|
https://www.indexdatabase.de/db/i-single.php?id=52
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return self.red / (self.nir + self.red + self.green)
|
return self.red / (self.nir + self.red + self.green)
|
||||||
|
|
||||||
def NGRDI(self):
|
def NGRDI(self):
|
||||||
"""
|
"""
|
||||||
Normalized Difference self.green/self.red Normalized self.green self.red
|
Normalized Difference self.green/self.red Normalized self.green self.red
|
||||||
difference index, Visible Atmospherically Resistant Indices self.green
|
difference index, Visible Atmospherically Resistant Indices self.green
|
||||||
(VIself.green)
|
(VIself.green)
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=390
|
https://www.indexdatabase.de/db/i-single.php?id=390
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.green - self.red) / (self.green + self.red)
|
return (self.green - self.red) / (self.green + self.red)
|
||||||
|
|
||||||
def RI(self):
|
def RI(self):
|
||||||
"""
|
"""
|
||||||
Normalized Difference self.red/self.green self.redness Index
|
Normalized Difference self.red/self.green self.redness Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=74
|
https://www.indexdatabase.de/db/i-single.php?id=74
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.red - self.green) / (self.red + self.green)
|
return (self.red - self.green) / (self.red + self.green)
|
||||||
|
|
||||||
def S(self):
|
def S(self):
|
||||||
"""
|
"""
|
||||||
Saturation
|
Saturation
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=77
|
https://www.indexdatabase.de/db/i-single.php?id=77
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
max = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)])
|
max = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)])
|
||||||
min = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)])
|
min = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)])
|
||||||
|
@ -503,26 +503,26 @@ class IndexCalculation:
|
||||||
|
|
||||||
def IF(self):
|
def IF(self):
|
||||||
"""
|
"""
|
||||||
Shape Index
|
Shape Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=79
|
https://www.indexdatabase.de/db/i-single.php?id=79
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (2 * self.red - self.green - self.blue) / (self.green - self.blue)
|
return (2 * self.red - self.green - self.blue) / (self.green - self.blue)
|
||||||
|
|
||||||
def DVI(self):
|
def DVI(self):
|
||||||
"""
|
"""
|
||||||
Simple Ratio self.nir/self.red Difference Vegetation Index, Vegetation Index
|
Simple Ratio self.nir/self.red Difference Vegetation Index, Vegetation Index
|
||||||
Number (VIN)
|
Number (VIN)
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=12
|
https://www.indexdatabase.de/db/i-single.php?id=12
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return self.nir / self.red
|
return self.nir / self.red
|
||||||
|
|
||||||
def TVI(self):
|
def TVI(self):
|
||||||
"""
|
"""
|
||||||
Transformed Vegetation Index
|
Transformed Vegetation Index
|
||||||
https://www.indexdatabase.de/db/i-single.php?id=98
|
https://www.indexdatabase.de/db/i-single.php?id=98
|
||||||
:return: index
|
:return: index
|
||||||
"""
|
"""
|
||||||
return (self.NDVI() + 0.5) ** (1 / 2)
|
return (self.NDVI() + 0.5) ** (1 / 2)
|
||||||
|
|
||||||
|
|
|
@ -82,7 +82,7 @@ def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")):
|
||||||
|
|
||||||
|
|
||||||
def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts):
|
def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts):
|
||||||
""" divide and conquer approach
|
"""divide and conquer approach
|
||||||
|
|
||||||
Parameters :
|
Parameters :
|
||||||
points, points_count (list(tuple(int, int)), int)
|
points, points_count (list(tuple(int, int)), int)
|
||||||
|
|
|
@ -11,7 +11,7 @@ Ref : INTRODUCTION TO ALGORITHMS THIRD EDITION
|
||||||
|
|
||||||
|
|
||||||
def max_sum_from_start(array):
|
def max_sum_from_start(array):
|
||||||
""" This function finds the maximum contiguous sum of array from 0 index
|
"""This function finds the maximum contiguous sum of array from 0 index
|
||||||
|
|
||||||
Parameters :
|
Parameters :
|
||||||
array (list[int]) : given array
|
array (list[int]) : given array
|
||||||
|
@ -30,7 +30,7 @@ def max_sum_from_start(array):
|
||||||
|
|
||||||
|
|
||||||
def max_cross_array_sum(array, left, mid, right):
|
def max_cross_array_sum(array, left, mid, right):
|
||||||
""" This function finds the maximum contiguous sum of left and right arrays
|
"""This function finds the maximum contiguous sum of left and right arrays
|
||||||
|
|
||||||
Parameters :
|
Parameters :
|
||||||
array, left, mid, right (list[int], int, int, int)
|
array, left, mid, right (list[int], int, int, int)
|
||||||
|
@ -46,7 +46,7 @@ def max_cross_array_sum(array, left, mid, right):
|
||||||
|
|
||||||
|
|
||||||
def max_subarray_sum(array, left, right):
|
def max_subarray_sum(array, left, right):
|
||||||
""" Maximum contiguous sub-array sum, using divide and conquer method
|
"""Maximum contiguous sub-array sum, using divide and conquer method
|
||||||
|
|
||||||
Parameters :
|
Parameters :
|
||||||
array, left, right (list[int], int, int) :
|
array, left, right (list[int], int, int) :
|
||||||
|
|
|
@ -29,7 +29,9 @@ def matrix_subtraction(matrix_a: List, matrix_b: List):
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def split_matrix(a: List,) -> Tuple[List, List, List, List]:
|
def split_matrix(
|
||||||
|
a: List,
|
||||||
|
) -> Tuple[List, List, List, List]:
|
||||||
"""
|
"""
|
||||||
Given an even length matrix, returns the top_left, top_right, bot_left, bot_right
|
Given an even length matrix, returns the top_left, top_right, bot_left, bot_right
|
||||||
quadrant.
|
quadrant.
|
||||||
|
|
|
@ -13,30 +13,30 @@ pieces separately or not cutting it at all if the price of it is the maximum obt
|
||||||
|
|
||||||
def naive_cut_rod_recursive(n: int, prices: list):
|
def naive_cut_rod_recursive(n: int, prices: list):
|
||||||
"""
|
"""
|
||||||
Solves the rod-cutting problem via naively without using the benefit of dynamic
|
Solves the rod-cutting problem via naively without using the benefit of dynamic
|
||||||
programming. The results is the same sub-problems are solved several times
|
programming. The results is the same sub-problems are solved several times
|
||||||
leading to an exponential runtime
|
leading to an exponential runtime
|
||||||
|
|
||||||
Runtime: O(2^n)
|
Runtime: O(2^n)
|
||||||
|
|
||||||
Arguments
|
Arguments
|
||||||
-------
|
-------
|
||||||
n: int, the length of the rod
|
n: int, the length of the rod
|
||||||
prices: list, the prices for each piece of rod. ``p[i-i]`` is the
|
prices: list, the prices for each piece of rod. ``p[i-i]`` is the
|
||||||
price for a rod of length ``i``
|
price for a rod of length ``i``
|
||||||
|
|
||||||
Returns
|
Returns
|
||||||
-------
|
-------
|
||||||
The maximum revenue obtainable for a rod of length n given the list of prices
|
The maximum revenue obtainable for a rod of length n given the list of prices
|
||||||
for each piece.
|
for each piece.
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
--------
|
--------
|
||||||
>>> naive_cut_rod_recursive(4, [1, 5, 8, 9])
|
>>> naive_cut_rod_recursive(4, [1, 5, 8, 9])
|
||||||
10
|
10
|
||||||
>>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30])
|
>>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30])
|
||||||
30
|
30
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_enforce_args(n, prices)
|
_enforce_args(n, prices)
|
||||||
if n == 0:
|
if n == 0:
|
||||||
|
@ -52,35 +52,35 @@ def naive_cut_rod_recursive(n: int, prices: list):
|
||||||
|
|
||||||
def top_down_cut_rod(n: int, prices: list):
|
def top_down_cut_rod(n: int, prices: list):
|
||||||
"""
|
"""
|
||||||
Constructs a top-down dynamic programming solution for the rod-cutting
|
Constructs a top-down dynamic programming solution for the rod-cutting
|
||||||
problem via memoization. This function serves as a wrapper for
|
problem via memoization. This function serves as a wrapper for
|
||||||
_top_down_cut_rod_recursive
|
_top_down_cut_rod_recursive
|
||||||
|
|
||||||
Runtime: O(n^2)
|
Runtime: O(n^2)
|
||||||
|
|
||||||
Arguments
|
Arguments
|
||||||
--------
|
--------
|
||||||
n: int, the length of the rod
|
n: int, the length of the rod
|
||||||
prices: list, the prices for each piece of rod. ``p[i-i]`` is the
|
prices: list, the prices for each piece of rod. ``p[i-i]`` is the
|
||||||
price for a rod of length ``i``
|
price for a rod of length ``i``
|
||||||
|
|
||||||
Note
|
Note
|
||||||
----
|
----
|
||||||
For convenience and because Python's lists using 0-indexing, length(max_rev) =
|
For convenience and because Python's lists using 0-indexing, length(max_rev) =
|
||||||
n + 1, to accommodate for the revenue obtainable from a rod of length 0.
|
n + 1, to accommodate for the revenue obtainable from a rod of length 0.
|
||||||
|
|
||||||
Returns
|
Returns
|
||||||
-------
|
-------
|
||||||
The maximum revenue obtainable for a rod of length n given the list of prices
|
The maximum revenue obtainable for a rod of length n given the list of prices
|
||||||
for each piece.
|
for each piece.
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
-------
|
-------
|
||||||
>>> top_down_cut_rod(4, [1, 5, 8, 9])
|
>>> top_down_cut_rod(4, [1, 5, 8, 9])
|
||||||
10
|
10
|
||||||
>>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30])
|
>>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30])
|
||||||
30
|
30
|
||||||
"""
|
"""
|
||||||
_enforce_args(n, prices)
|
_enforce_args(n, prices)
|
||||||
max_rev = [float("-inf") for _ in range(n + 1)]
|
max_rev = [float("-inf") for _ in range(n + 1)]
|
||||||
return _top_down_cut_rod_recursive(n, prices, max_rev)
|
return _top_down_cut_rod_recursive(n, prices, max_rev)
|
||||||
|
@ -88,24 +88,24 @@ def top_down_cut_rod(n: int, prices: list):
|
||||||
|
|
||||||
def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list):
|
def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list):
|
||||||
"""
|
"""
|
||||||
Constructs a top-down dynamic programming solution for the rod-cutting problem
|
Constructs a top-down dynamic programming solution for the rod-cutting problem
|
||||||
via memoization.
|
via memoization.
|
||||||
|
|
||||||
Runtime: O(n^2)
|
Runtime: O(n^2)
|
||||||
|
|
||||||
Arguments
|
Arguments
|
||||||
--------
|
--------
|
||||||
n: int, the length of the rod
|
n: int, the length of the rod
|
||||||
prices: list, the prices for each piece of rod. ``p[i-i]`` is the
|
prices: list, the prices for each piece of rod. ``p[i-i]`` is the
|
||||||
price for a rod of length ``i``
|
price for a rod of length ``i``
|
||||||
max_rev: list, the computed maximum revenue for a piece of rod.
|
max_rev: list, the computed maximum revenue for a piece of rod.
|
||||||
``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i``
|
``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i``
|
||||||
|
|
||||||
Returns
|
Returns
|
||||||
-------
|
-------
|
||||||
The maximum revenue obtainable for a rod of length n given the list of prices
|
The maximum revenue obtainable for a rod of length n given the list of prices
|
||||||
for each piece.
|
for each piece.
|
||||||
"""
|
"""
|
||||||
if max_rev[n] >= 0:
|
if max_rev[n] >= 0:
|
||||||
return max_rev[n]
|
return max_rev[n]
|
||||||
elif n == 0:
|
elif n == 0:
|
||||||
|
@ -125,28 +125,28 @@ def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list):
|
||||||
|
|
||||||
def bottom_up_cut_rod(n: int, prices: list):
|
def bottom_up_cut_rod(n: int, prices: list):
|
||||||
"""
|
"""
|
||||||
Constructs a bottom-up dynamic programming solution for the rod-cutting problem
|
Constructs a bottom-up dynamic programming solution for the rod-cutting problem
|
||||||
|
|
||||||
Runtime: O(n^2)
|
Runtime: O(n^2)
|
||||||
|
|
||||||
Arguments
|
Arguments
|
||||||
----------
|
----------
|
||||||
n: int, the maximum length of the rod.
|
n: int, the maximum length of the rod.
|
||||||
prices: list, the prices for each piece of rod. ``p[i-i]`` is the
|
prices: list, the prices for each piece of rod. ``p[i-i]`` is the
|
||||||
price for a rod of length ``i``
|
price for a rod of length ``i``
|
||||||
|
|
||||||
Returns
|
Returns
|
||||||
-------
|
-------
|
||||||
The maximum revenue obtainable from cutting a rod of length n given
|
The maximum revenue obtainable from cutting a rod of length n given
|
||||||
the prices for each piece of rod p.
|
the prices for each piece of rod p.
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
-------
|
-------
|
||||||
>>> bottom_up_cut_rod(4, [1, 5, 8, 9])
|
>>> bottom_up_cut_rod(4, [1, 5, 8, 9])
|
||||||
10
|
10
|
||||||
>>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30])
|
>>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30])
|
||||||
30
|
30
|
||||||
"""
|
"""
|
||||||
_enforce_args(n, prices)
|
_enforce_args(n, prices)
|
||||||
|
|
||||||
# length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of
|
# length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of
|
||||||
|
@ -166,16 +166,16 @@ def bottom_up_cut_rod(n: int, prices: list):
|
||||||
|
|
||||||
def _enforce_args(n: int, prices: list):
|
def _enforce_args(n: int, prices: list):
|
||||||
"""
|
"""
|
||||||
Basic checks on the arguments to the rod-cutting algorithms
|
Basic checks on the arguments to the rod-cutting algorithms
|
||||||
|
|
||||||
n: int, the length of the rod
|
n: int, the length of the rod
|
||||||
prices: list, the price list for each piece of rod.
|
prices: list, the price list for each piece of rod.
|
||||||
|
|
||||||
Throws ValueError:
|
Throws ValueError:
|
||||||
|
|
||||||
if n is negative or there are fewer items in the price list than the length of
|
if n is negative or there are fewer items in the price list than the length of
|
||||||
the rod
|
the rod
|
||||||
"""
|
"""
|
||||||
if n < 0:
|
if n < 0:
|
||||||
raise ValueError(f"n must be greater than or equal to 0. Got n = {n}")
|
raise ValueError(f"n must be greater than or equal to 0. Got n = {n}")
|
||||||
|
|
||||||
|
|
|
@ -20,18 +20,18 @@ graph = {
|
||||||
def bfs_shortest_path(graph: dict, start, goal) -> str:
|
def bfs_shortest_path(graph: dict, start, goal) -> str:
|
||||||
"""Find shortest path between `start` and `goal` nodes.
|
"""Find shortest path between `start` and `goal` nodes.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
graph (dict): node/list of neighboring nodes key/value pairs.
|
graph (dict): node/list of neighboring nodes key/value pairs.
|
||||||
start: start node.
|
start: start node.
|
||||||
goal: target node.
|
goal: target node.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Shortest path between `start` and `goal` nodes as a string of nodes.
|
Shortest path between `start` and `goal` nodes as a string of nodes.
|
||||||
'Not found' string if no path found.
|
'Not found' string if no path found.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
>>> bfs_shortest_path(graph, "G", "D")
|
>>> bfs_shortest_path(graph, "G", "D")
|
||||||
['G', 'C', 'A', 'B', 'D']
|
['G', 'C', 'A', 'B', 'D']
|
||||||
"""
|
"""
|
||||||
# keep track of explored nodes
|
# keep track of explored nodes
|
||||||
explored = []
|
explored = []
|
||||||
|
@ -70,22 +70,22 @@ def bfs_shortest_path(graph: dict, start, goal) -> str:
|
||||||
def bfs_shortest_path_distance(graph: dict, start, target) -> int:
|
def bfs_shortest_path_distance(graph: dict, start, target) -> int:
|
||||||
"""Find shortest path distance between `start` and `target` nodes.
|
"""Find shortest path distance between `start` and `target` nodes.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
graph: node/list of neighboring nodes key/value pairs.
|
graph: node/list of neighboring nodes key/value pairs.
|
||||||
start: node to start search from.
|
start: node to start search from.
|
||||||
target: node to search for.
|
target: node to search for.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Number of edges in shortest path between `start` and `target` nodes.
|
Number of edges in shortest path between `start` and `target` nodes.
|
||||||
-1 if no path exists.
|
-1 if no path exists.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
>>> bfs_shortest_path_distance(graph, "G", "D")
|
>>> bfs_shortest_path_distance(graph, "G", "D")
|
||||||
4
|
4
|
||||||
>>> bfs_shortest_path_distance(graph, "A", "A")
|
>>> bfs_shortest_path_distance(graph, "A", "A")
|
||||||
0
|
0
|
||||||
>>> bfs_shortest_path_distance(graph, "A", "H")
|
>>> bfs_shortest_path_distance(graph, "A", "H")
|
||||||
-1
|
-1
|
||||||
"""
|
"""
|
||||||
if not graph or start not in graph or target not in graph:
|
if not graph or start not in graph or target not in graph:
|
||||||
return -1
|
return -1
|
||||||
|
|
|
@ -17,18 +17,18 @@ from typing import Dict, Set
|
||||||
def depth_first_search(graph: Dict, start: str) -> Set[int]:
|
def depth_first_search(graph: Dict, start: str) -> Set[int]:
|
||||||
"""Depth First Search on Graph
|
"""Depth First Search on Graph
|
||||||
|
|
||||||
:param graph: directed graph in dictionary format
|
:param graph: directed graph in dictionary format
|
||||||
:param vertex: starting vectex as a string
|
:param vertex: starting vectex as a string
|
||||||
:returns: the trace of the search
|
:returns: the trace of the search
|
||||||
>>> G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"],
|
>>> G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"],
|
||||||
... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"],
|
... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"],
|
||||||
... "F": ["C", "E", "G"], "G": ["F"] }
|
... "F": ["C", "E", "G"], "G": ["F"] }
|
||||||
>>> start = "A"
|
>>> start = "A"
|
||||||
>>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'})
|
>>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'})
|
||||||
>>> all(x in output_G for x in list(depth_first_search(G, "A")))
|
>>> all(x in output_G for x in list(depth_first_search(G, "A")))
|
||||||
True
|
True
|
||||||
>>> all(x in output_G for x in list(depth_first_search(G, "G")))
|
>>> all(x in output_G for x in list(depth_first_search(G, "G")))
|
||||||
True
|
True
|
||||||
"""
|
"""
|
||||||
explored, stack = set(start), [start]
|
explored, stack = set(start), [start]
|
||||||
while stack:
|
while stack:
|
||||||
|
|
|
@ -56,14 +56,14 @@ def connect(graph, a, b, edge):
|
||||||
def prim(graph: list, root: Vertex) -> list:
|
def prim(graph: list, root: Vertex) -> list:
|
||||||
"""Prim's Algorithm.
|
"""Prim's Algorithm.
|
||||||
|
|
||||||
Runtime:
|
Runtime:
|
||||||
O(mn) with `m` edges and `n` vertices
|
O(mn) with `m` edges and `n` vertices
|
||||||
|
|
||||||
Return:
|
Return:
|
||||||
List with the edges of a Minimum Spanning Tree
|
List with the edges of a Minimum Spanning Tree
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
prim(graph, graph[0])
|
prim(graph, graph[0])
|
||||||
"""
|
"""
|
||||||
a = []
|
a = []
|
||||||
for u in graph:
|
for u in graph:
|
||||||
|
@ -86,14 +86,14 @@ def prim(graph: list, root: Vertex) -> list:
|
||||||
def prim_heap(graph: list, root: Vertex) -> Iterator[tuple]:
|
def prim_heap(graph: list, root: Vertex) -> Iterator[tuple]:
|
||||||
"""Prim's Algorithm with min heap.
|
"""Prim's Algorithm with min heap.
|
||||||
|
|
||||||
Runtime:
|
Runtime:
|
||||||
O((m + n)log n) with `m` edges and `n` vertices
|
O((m + n)log n) with `m` edges and `n` vertices
|
||||||
|
|
||||||
Yield:
|
Yield:
|
||||||
Edges of a Minimum Spanning Tree
|
Edges of a Minimum Spanning Tree
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
prim(graph, graph[0])
|
prim(graph, graph[0])
|
||||||
"""
|
"""
|
||||||
for u in graph:
|
for u in graph:
|
||||||
u.key = math.inf
|
u.key = math.inf
|
||||||
|
|
|
@ -94,9 +94,7 @@ def not32(i):
|
||||||
|
|
||||||
|
|
||||||
def sum32(a, b):
|
def sum32(a, b):
|
||||||
"""
|
""""""
|
||||||
|
|
||||||
"""
|
|
||||||
return (a + b) % 2 ** 32
|
return (a + b) % 2 ** 32
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -26,29 +26,29 @@ import random
|
||||||
|
|
||||||
class Vector:
|
class Vector:
|
||||||
"""
|
"""
|
||||||
This class represents a vector of arbitrary size.
|
This class represents a vector of arbitrary size.
|
||||||
You need to give the vector components.
|
You need to give the vector components.
|
||||||
|
|
||||||
Overview about the methods:
|
Overview about the methods:
|
||||||
|
|
||||||
constructor(components : list) : init the vector
|
constructor(components : list) : init the vector
|
||||||
set(components : list) : changes the vector components.
|
set(components : list) : changes the vector components.
|
||||||
__str__() : toString method
|
__str__() : toString method
|
||||||
component(i : int): gets the i-th component (start by 0)
|
component(i : int): gets the i-th component (start by 0)
|
||||||
__len__() : gets the size of the vector (number of components)
|
__len__() : gets the size of the vector (number of components)
|
||||||
euclidLength() : returns the euclidean length of the vector.
|
euclidLength() : returns the euclidean length of the vector.
|
||||||
operator + : vector addition
|
operator + : vector addition
|
||||||
operator - : vector subtraction
|
operator - : vector subtraction
|
||||||
operator * : scalar multiplication and dot product
|
operator * : scalar multiplication and dot product
|
||||||
copy() : copies this vector and returns it.
|
copy() : copies this vector and returns it.
|
||||||
changeComponent(pos,value) : changes the specified component.
|
changeComponent(pos,value) : changes the specified component.
|
||||||
TODO: compare-operator
|
TODO: compare-operator
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, components=None):
|
def __init__(self, components=None):
|
||||||
"""
|
"""
|
||||||
input: components or nothing
|
input: components or nothing
|
||||||
simple constructor for init the vector
|
simple constructor for init the vector
|
||||||
"""
|
"""
|
||||||
if components is None:
|
if components is None:
|
||||||
components = []
|
components = []
|
||||||
|
@ -56,9 +56,9 @@ class Vector:
|
||||||
|
|
||||||
def set(self, components):
|
def set(self, components):
|
||||||
"""
|
"""
|
||||||
input: new components
|
input: new components
|
||||||
changes the components of the vector.
|
changes the components of the vector.
|
||||||
replace the components with newer one.
|
replace the components with newer one.
|
||||||
"""
|
"""
|
||||||
if len(components) > 0:
|
if len(components) > 0:
|
||||||
self.__components = list(components)
|
self.__components = list(components)
|
||||||
|
@ -67,14 +67,14 @@ class Vector:
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
"""
|
"""
|
||||||
returns a string representation of the vector
|
returns a string representation of the vector
|
||||||
"""
|
"""
|
||||||
return "(" + ",".join(map(str, self.__components)) + ")"
|
return "(" + ",".join(map(str, self.__components)) + ")"
|
||||||
|
|
||||||
def component(self, i):
|
def component(self, i):
|
||||||
"""
|
"""
|
||||||
input: index (start at 0)
|
input: index (start at 0)
|
||||||
output: the i-th component of the vector.
|
output: the i-th component of the vector.
|
||||||
"""
|
"""
|
||||||
if type(i) is int and -len(self.__components) <= i < len(self.__components):
|
if type(i) is int and -len(self.__components) <= i < len(self.__components):
|
||||||
return self.__components[i]
|
return self.__components[i]
|
||||||
|
@ -83,13 +83,13 @@ class Vector:
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
"""
|
"""
|
||||||
returns the size of the vector
|
returns the size of the vector
|
||||||
"""
|
"""
|
||||||
return len(self.__components)
|
return len(self.__components)
|
||||||
|
|
||||||
def euclidLength(self):
|
def euclidLength(self):
|
||||||
"""
|
"""
|
||||||
returns the euclidean length of the vector
|
returns the euclidean length of the vector
|
||||||
"""
|
"""
|
||||||
summe = 0
|
summe = 0
|
||||||
for c in self.__components:
|
for c in self.__components:
|
||||||
|
@ -98,9 +98,9 @@ class Vector:
|
||||||
|
|
||||||
def __add__(self, other):
|
def __add__(self, other):
|
||||||
"""
|
"""
|
||||||
input: other vector
|
input: other vector
|
||||||
assumes: other vector has the same size
|
assumes: other vector has the same size
|
||||||
returns a new vector that represents the sum.
|
returns a new vector that represents the sum.
|
||||||
"""
|
"""
|
||||||
size = len(self)
|
size = len(self)
|
||||||
if size == len(other):
|
if size == len(other):
|
||||||
|
@ -111,9 +111,9 @@ class Vector:
|
||||||
|
|
||||||
def __sub__(self, other):
|
def __sub__(self, other):
|
||||||
"""
|
"""
|
||||||
input: other vector
|
input: other vector
|
||||||
assumes: other vector has the same size
|
assumes: other vector has the same size
|
||||||
returns a new vector that represents the difference.
|
returns a new vector that represents the difference.
|
||||||
"""
|
"""
|
||||||
size = len(self)
|
size = len(self)
|
||||||
if size == len(other):
|
if size == len(other):
|
||||||
|
@ -124,8 +124,8 @@ class Vector:
|
||||||
|
|
||||||
def __mul__(self, other):
|
def __mul__(self, other):
|
||||||
"""
|
"""
|
||||||
mul implements the scalar multiplication
|
mul implements the scalar multiplication
|
||||||
and the dot-product
|
and the dot-product
|
||||||
"""
|
"""
|
||||||
if isinstance(other, float) or isinstance(other, int):
|
if isinstance(other, float) or isinstance(other, int):
|
||||||
ans = [c * other for c in self.__components]
|
ans = [c * other for c in self.__components]
|
||||||
|
@ -141,15 +141,15 @@ class Vector:
|
||||||
|
|
||||||
def copy(self):
|
def copy(self):
|
||||||
"""
|
"""
|
||||||
copies this vector and returns it.
|
copies this vector and returns it.
|
||||||
"""
|
"""
|
||||||
return Vector(self.__components)
|
return Vector(self.__components)
|
||||||
|
|
||||||
def changeComponent(self, pos, value):
|
def changeComponent(self, pos, value):
|
||||||
"""
|
"""
|
||||||
input: an index (pos) and a value
|
input: an index (pos) and a value
|
||||||
changes the specified component (pos) with the
|
changes the specified component (pos) with the
|
||||||
'value'
|
'value'
|
||||||
"""
|
"""
|
||||||
# precondition
|
# precondition
|
||||||
assert -len(self.__components) <= pos < len(self.__components)
|
assert -len(self.__components) <= pos < len(self.__components)
|
||||||
|
@ -158,7 +158,7 @@ class Vector:
|
||||||
|
|
||||||
def zeroVector(dimension):
|
def zeroVector(dimension):
|
||||||
"""
|
"""
|
||||||
returns a zero-vector of size 'dimension'
|
returns a zero-vector of size 'dimension'
|
||||||
"""
|
"""
|
||||||
# precondition
|
# precondition
|
||||||
assert isinstance(dimension, int)
|
assert isinstance(dimension, int)
|
||||||
|
@ -167,8 +167,8 @@ def zeroVector(dimension):
|
||||||
|
|
||||||
def unitBasisVector(dimension, pos):
|
def unitBasisVector(dimension, pos):
|
||||||
"""
|
"""
|
||||||
returns a unit basis vector with a One
|
returns a unit basis vector with a One
|
||||||
at index 'pos' (indexing at 0)
|
at index 'pos' (indexing at 0)
|
||||||
"""
|
"""
|
||||||
# precondition
|
# precondition
|
||||||
assert isinstance(dimension, int) and (isinstance(pos, int))
|
assert isinstance(dimension, int) and (isinstance(pos, int))
|
||||||
|
@ -179,9 +179,9 @@ def unitBasisVector(dimension, pos):
|
||||||
|
|
||||||
def axpy(scalar, x, y):
|
def axpy(scalar, x, y):
|
||||||
"""
|
"""
|
||||||
input: a 'scalar' and two vectors 'x' and 'y'
|
input: a 'scalar' and two vectors 'x' and 'y'
|
||||||
output: a vector
|
output: a vector
|
||||||
computes the axpy operation
|
computes the axpy operation
|
||||||
"""
|
"""
|
||||||
# precondition
|
# precondition
|
||||||
assert (
|
assert (
|
||||||
|
@ -194,10 +194,10 @@ def axpy(scalar, x, y):
|
||||||
|
|
||||||
def randomVector(N, a, b):
|
def randomVector(N, a, b):
|
||||||
"""
|
"""
|
||||||
input: size (N) of the vector.
|
input: size (N) of the vector.
|
||||||
random range (a,b)
|
random range (a,b)
|
||||||
output: returns a random vector of size N, with
|
output: returns a random vector of size N, with
|
||||||
random integer components between 'a' and 'b'.
|
random integer components between 'a' and 'b'.
|
||||||
"""
|
"""
|
||||||
random.seed(None)
|
random.seed(None)
|
||||||
ans = [random.randint(a, b) for i in range(N)]
|
ans = [random.randint(a, b) for i in range(N)]
|
||||||
|
@ -224,8 +224,8 @@ class Matrix:
|
||||||
|
|
||||||
def __init__(self, matrix, w, h):
|
def __init__(self, matrix, w, h):
|
||||||
"""
|
"""
|
||||||
simple constructor for initializing
|
simple constructor for initializing
|
||||||
the matrix with components.
|
the matrix with components.
|
||||||
"""
|
"""
|
||||||
self.__matrix = matrix
|
self.__matrix = matrix
|
||||||
self.__width = w
|
self.__width = w
|
||||||
|
@ -233,8 +233,8 @@ class Matrix:
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
"""
|
"""
|
||||||
returns a string representation of this
|
returns a string representation of this
|
||||||
matrix.
|
matrix.
|
||||||
"""
|
"""
|
||||||
ans = ""
|
ans = ""
|
||||||
for i in range(self.__height):
|
for i in range(self.__height):
|
||||||
|
@ -248,7 +248,7 @@ class Matrix:
|
||||||
|
|
||||||
def changeComponent(self, x, y, value):
|
def changeComponent(self, x, y, value):
|
||||||
"""
|
"""
|
||||||
changes the x-y component of this matrix
|
changes the x-y component of this matrix
|
||||||
"""
|
"""
|
||||||
if 0 <= x < self.__height and 0 <= y < self.__width:
|
if 0 <= x < self.__height and 0 <= y < self.__width:
|
||||||
self.__matrix[x][y] = value
|
self.__matrix[x][y] = value
|
||||||
|
@ -257,7 +257,7 @@ class Matrix:
|
||||||
|
|
||||||
def component(self, x, y):
|
def component(self, x, y):
|
||||||
"""
|
"""
|
||||||
returns the specified (x,y) component
|
returns the specified (x,y) component
|
||||||
"""
|
"""
|
||||||
if 0 <= x < self.__height and 0 <= y < self.__width:
|
if 0 <= x < self.__height and 0 <= y < self.__width:
|
||||||
return self.__matrix[x][y]
|
return self.__matrix[x][y]
|
||||||
|
@ -266,19 +266,19 @@ class Matrix:
|
||||||
|
|
||||||
def width(self):
|
def width(self):
|
||||||
"""
|
"""
|
||||||
getter for the width
|
getter for the width
|
||||||
"""
|
"""
|
||||||
return self.__width
|
return self.__width
|
||||||
|
|
||||||
def height(self):
|
def height(self):
|
||||||
"""
|
"""
|
||||||
getter for the height
|
getter for the height
|
||||||
"""
|
"""
|
||||||
return self.__height
|
return self.__height
|
||||||
|
|
||||||
def determinate(self) -> float:
|
def determinate(self) -> float:
|
||||||
"""
|
"""
|
||||||
returns the determinate of an nxn matrix using Laplace expansion
|
returns the determinate of an nxn matrix using Laplace expansion
|
||||||
"""
|
"""
|
||||||
if self.__height == self.__width and self.__width >= 2:
|
if self.__height == self.__width and self.__width >= 2:
|
||||||
total = 0
|
total = 0
|
||||||
|
@ -305,8 +305,8 @@ class Matrix:
|
||||||
|
|
||||||
def __mul__(self, other):
|
def __mul__(self, other):
|
||||||
"""
|
"""
|
||||||
implements the matrix-vector multiplication.
|
implements the matrix-vector multiplication.
|
||||||
implements the matrix-scalar multiplication
|
implements the matrix-scalar multiplication
|
||||||
"""
|
"""
|
||||||
if isinstance(other, Vector): # vector-matrix
|
if isinstance(other, Vector): # vector-matrix
|
||||||
if len(other) == self.__width:
|
if len(other) == self.__width:
|
||||||
|
@ -332,7 +332,7 @@ class Matrix:
|
||||||
|
|
||||||
def __add__(self, other):
|
def __add__(self, other):
|
||||||
"""
|
"""
|
||||||
implements the matrix-addition.
|
implements the matrix-addition.
|
||||||
"""
|
"""
|
||||||
if self.__width == other.width() and self.__height == other.height():
|
if self.__width == other.width() and self.__height == other.height():
|
||||||
matrix = []
|
matrix = []
|
||||||
|
@ -347,7 +347,7 @@ class Matrix:
|
||||||
|
|
||||||
def __sub__(self, other):
|
def __sub__(self, other):
|
||||||
"""
|
"""
|
||||||
implements the matrix-subtraction.
|
implements the matrix-subtraction.
|
||||||
"""
|
"""
|
||||||
if self.__width == other.width() and self.__height == other.height():
|
if self.__width == other.width() and self.__height == other.height():
|
||||||
matrix = []
|
matrix = []
|
||||||
|
@ -363,7 +363,7 @@ class Matrix:
|
||||||
|
|
||||||
def squareZeroMatrix(N):
|
def squareZeroMatrix(N):
|
||||||
"""
|
"""
|
||||||
returns a square zero-matrix of dimension NxN
|
returns a square zero-matrix of dimension NxN
|
||||||
"""
|
"""
|
||||||
ans = [[0] * N for i in range(N)]
|
ans = [[0] * N for i in range(N)]
|
||||||
return Matrix(ans, N, N)
|
return Matrix(ans, N, N)
|
||||||
|
@ -371,8 +371,8 @@ def squareZeroMatrix(N):
|
||||||
|
|
||||||
def randomMatrix(W, H, a, b):
|
def randomMatrix(W, H, a, b):
|
||||||
"""
|
"""
|
||||||
returns a random matrix WxH with integer components
|
returns a random matrix WxH with integer components
|
||||||
between 'a' and 'b'
|
between 'a' and 'b'
|
||||||
"""
|
"""
|
||||||
random.seed(None)
|
random.seed(None)
|
||||||
matrix = [[random.randint(a, b) for j in range(W)] for i in range(H)]
|
matrix = [[random.randint(a, b) for j in range(W)] for i in range(H)]
|
||||||
|
|
|
@ -14,7 +14,7 @@ from lib import Matrix, Vector, axpy, squareZeroMatrix, unitBasisVector, zeroVec
|
||||||
class Test(unittest.TestCase):
|
class Test(unittest.TestCase):
|
||||||
def test_component(self):
|
def test_component(self):
|
||||||
"""
|
"""
|
||||||
test for method component
|
test for method component
|
||||||
"""
|
"""
|
||||||
x = Vector([1, 2, 3])
|
x = Vector([1, 2, 3])
|
||||||
self.assertEqual(x.component(0), 1)
|
self.assertEqual(x.component(0), 1)
|
||||||
|
@ -23,28 +23,28 @@ class Test(unittest.TestCase):
|
||||||
|
|
||||||
def test_str(self):
|
def test_str(self):
|
||||||
"""
|
"""
|
||||||
test for toString() method
|
test for toString() method
|
||||||
"""
|
"""
|
||||||
x = Vector([0, 0, 0, 0, 0, 1])
|
x = Vector([0, 0, 0, 0, 0, 1])
|
||||||
self.assertEqual(str(x), "(0,0,0,0,0,1)")
|
self.assertEqual(str(x), "(0,0,0,0,0,1)")
|
||||||
|
|
||||||
def test_size(self):
|
def test_size(self):
|
||||||
"""
|
"""
|
||||||
test for size()-method
|
test for size()-method
|
||||||
"""
|
"""
|
||||||
x = Vector([1, 2, 3, 4])
|
x = Vector([1, 2, 3, 4])
|
||||||
self.assertEqual(len(x), 4)
|
self.assertEqual(len(x), 4)
|
||||||
|
|
||||||
def test_euclidLength(self):
|
def test_euclidLength(self):
|
||||||
"""
|
"""
|
||||||
test for the eulidean length
|
test for the eulidean length
|
||||||
"""
|
"""
|
||||||
x = Vector([1, 2])
|
x = Vector([1, 2])
|
||||||
self.assertAlmostEqual(x.euclidLength(), 2.236, 3)
|
self.assertAlmostEqual(x.euclidLength(), 2.236, 3)
|
||||||
|
|
||||||
def test_add(self):
|
def test_add(self):
|
||||||
"""
|
"""
|
||||||
test for + operator
|
test for + operator
|
||||||
"""
|
"""
|
||||||
x = Vector([1, 2, 3])
|
x = Vector([1, 2, 3])
|
||||||
y = Vector([1, 1, 1])
|
y = Vector([1, 1, 1])
|
||||||
|
@ -54,7 +54,7 @@ class Test(unittest.TestCase):
|
||||||
|
|
||||||
def test_sub(self):
|
def test_sub(self):
|
||||||
"""
|
"""
|
||||||
test for - operator
|
test for - operator
|
||||||
"""
|
"""
|
||||||
x = Vector([1, 2, 3])
|
x = Vector([1, 2, 3])
|
||||||
y = Vector([1, 1, 1])
|
y = Vector([1, 1, 1])
|
||||||
|
@ -64,7 +64,7 @@ class Test(unittest.TestCase):
|
||||||
|
|
||||||
def test_mul(self):
|
def test_mul(self):
|
||||||
"""
|
"""
|
||||||
test for * operator
|
test for * operator
|
||||||
"""
|
"""
|
||||||
x = Vector([1, 2, 3])
|
x = Vector([1, 2, 3])
|
||||||
a = Vector([2, -1, 4]) # for test of dot-product
|
a = Vector([2, -1, 4]) # for test of dot-product
|
||||||
|
@ -74,19 +74,19 @@ class Test(unittest.TestCase):
|
||||||
|
|
||||||
def test_zeroVector(self):
|
def test_zeroVector(self):
|
||||||
"""
|
"""
|
||||||
test for the global function zeroVector(...)
|
test for the global function zeroVector(...)
|
||||||
"""
|
"""
|
||||||
self.assertTrue(str(zeroVector(10)).count("0") == 10)
|
self.assertTrue(str(zeroVector(10)).count("0") == 10)
|
||||||
|
|
||||||
def test_unitBasisVector(self):
|
def test_unitBasisVector(self):
|
||||||
"""
|
"""
|
||||||
test for the global function unitBasisVector(...)
|
test for the global function unitBasisVector(...)
|
||||||
"""
|
"""
|
||||||
self.assertEqual(str(unitBasisVector(3, 1)), "(0,1,0)")
|
self.assertEqual(str(unitBasisVector(3, 1)), "(0,1,0)")
|
||||||
|
|
||||||
def test_axpy(self):
|
def test_axpy(self):
|
||||||
"""
|
"""
|
||||||
test for the global function axpy(...) (operation)
|
test for the global function axpy(...) (operation)
|
||||||
"""
|
"""
|
||||||
x = Vector([1, 2, 3])
|
x = Vector([1, 2, 3])
|
||||||
y = Vector([1, 0, 1])
|
y = Vector([1, 0, 1])
|
||||||
|
@ -94,7 +94,7 @@ class Test(unittest.TestCase):
|
||||||
|
|
||||||
def test_copy(self):
|
def test_copy(self):
|
||||||
"""
|
"""
|
||||||
test for the copy()-method
|
test for the copy()-method
|
||||||
"""
|
"""
|
||||||
x = Vector([1, 0, 0, 0, 0, 0])
|
x = Vector([1, 0, 0, 0, 0, 0])
|
||||||
y = x.copy()
|
y = x.copy()
|
||||||
|
@ -102,7 +102,7 @@ class Test(unittest.TestCase):
|
||||||
|
|
||||||
def test_changeComponent(self):
|
def test_changeComponent(self):
|
||||||
"""
|
"""
|
||||||
test for the changeComponent(...)-method
|
test for the changeComponent(...)-method
|
||||||
"""
|
"""
|
||||||
x = Vector([1, 0, 0])
|
x = Vector([1, 0, 0])
|
||||||
x.changeComponent(0, 0)
|
x.changeComponent(0, 0)
|
||||||
|
@ -115,7 +115,7 @@ class Test(unittest.TestCase):
|
||||||
|
|
||||||
def test_determinate(self):
|
def test_determinate(self):
|
||||||
"""
|
"""
|
||||||
test for determinate()
|
test for determinate()
|
||||||
"""
|
"""
|
||||||
A = Matrix([[1, 1, 4, 5], [3, 3, 3, 2], [5, 1, 9, 0], [9, 7, 7, 9]], 4, 4)
|
A = Matrix([[1, 1, 4, 5], [3, 3, 3, 2], [5, 1, 9, 0], [9, 7, 7, 9]], 4, 4)
|
||||||
self.assertEqual(-376, A.determinate())
|
self.assertEqual(-376, A.determinate())
|
||||||
|
|
|
@ -135,8 +135,7 @@ class Decision_Tree:
|
||||||
|
|
||||||
|
|
||||||
class Test_Decision_Tree:
|
class Test_Decision_Tree:
|
||||||
"""Decision Tres test class
|
"""Decision Tres test class"""
|
||||||
"""
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def helper_mean_squared_error_test(labels, prediction):
|
def helper_mean_squared_error_test(labels, prediction):
|
||||||
|
|
|
@ -132,12 +132,12 @@ def kmeans(
|
||||||
data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False
|
data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False
|
||||||
):
|
):
|
||||||
"""This function runs k-means on given data and initial set of centroids.
|
"""This function runs k-means on given data and initial set of centroids.
|
||||||
maxiter: maximum number of iterations to run.(default=500)
|
maxiter: maximum number of iterations to run.(default=500)
|
||||||
record_heterogeneity: (optional) a list, to store the history of heterogeneity
|
record_heterogeneity: (optional) a list, to store the history of heterogeneity
|
||||||
as function of iterations
|
as function of iterations
|
||||||
if None, do not store the history.
|
if None, do not store the history.
|
||||||
verbose: if True, print how many data points changed their cluster labels in
|
verbose: if True, print how many data points changed their cluster labels in
|
||||||
each iteration"""
|
each iteration"""
|
||||||
centroids = initial_centroids[:]
|
centroids = initial_centroids[:]
|
||||||
prev_cluster_assignment = None
|
prev_cluster_assignment = None
|
||||||
|
|
||||||
|
|
|
@ -153,7 +153,7 @@ def calculate_variance(items: list, means: list, total_count: int) -> float:
|
||||||
def predict_y_values(
|
def predict_y_values(
|
||||||
x_items: list, means: list, variance: float, probabilities: list
|
x_items: list, means: list, variance: float, probabilities: list
|
||||||
) -> list:
|
) -> list:
|
||||||
""" This function predicts new indexes(groups for our data)
|
"""This function predicts new indexes(groups for our data)
|
||||||
:param x_items: a list containing all items(gaussian distribution of all classes)
|
:param x_items: a list containing all items(gaussian distribution of all classes)
|
||||||
:param means: a list containing real mean values of each class
|
:param means: a list containing real mean values of each class
|
||||||
:param variance: calculated value of variance by calculate_variance function
|
:param variance: calculated value of variance by calculate_variance function
|
||||||
|
|
|
@ -12,7 +12,7 @@ import requests
|
||||||
|
|
||||||
|
|
||||||
def collect_dataset():
|
def collect_dataset():
|
||||||
""" Collect dataset of CSGO
|
"""Collect dataset of CSGO
|
||||||
The dataset contains ADR vs Rating of a Player
|
The dataset contains ADR vs Rating of a Player
|
||||||
:return : dataset obtained from the link, as matrix
|
:return : dataset obtained from the link, as matrix
|
||||||
"""
|
"""
|
||||||
|
@ -32,7 +32,7 @@ def collect_dataset():
|
||||||
|
|
||||||
|
|
||||||
def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta):
|
def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta):
|
||||||
""" Run steep gradient descent and updates the Feature vector accordingly_
|
"""Run steep gradient descent and updates the Feature vector accordingly_
|
||||||
:param data_x : contains the dataset
|
:param data_x : contains the dataset
|
||||||
:param data_y : contains the output associated with each data-entry
|
:param data_y : contains the output associated with each data-entry
|
||||||
:param len_data : length of the data_
|
:param len_data : length of the data_
|
||||||
|
@ -51,7 +51,7 @@ def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta):
|
||||||
|
|
||||||
|
|
||||||
def sum_of_square_error(data_x, data_y, len_data, theta):
|
def sum_of_square_error(data_x, data_y, len_data, theta):
|
||||||
""" Return sum of square error for error calculation
|
"""Return sum of square error for error calculation
|
||||||
:param data_x : contains our dataset
|
:param data_x : contains our dataset
|
||||||
:param data_y : contains the output (result vector)
|
:param data_y : contains the output (result vector)
|
||||||
:param len_data : len of the dataset
|
:param len_data : len of the dataset
|
||||||
|
@ -66,7 +66,7 @@ def sum_of_square_error(data_x, data_y, len_data, theta):
|
||||||
|
|
||||||
|
|
||||||
def run_linear_regression(data_x, data_y):
|
def run_linear_regression(data_x, data_y):
|
||||||
""" Implement Linear regression over the dataset
|
"""Implement Linear regression over the dataset
|
||||||
:param data_x : contains our dataset
|
:param data_x : contains our dataset
|
||||||
:param data_y : contains the output (result vector)
|
:param data_y : contains the output (result vector)
|
||||||
:return : feature for line of best fit (Feature vector)
|
:return : feature for line of best fit (Feature vector)
|
||||||
|
|
|
@ -1,18 +1,18 @@
|
||||||
def kthPermutation(k, n):
|
def kthPermutation(k, n):
|
||||||
"""
|
"""
|
||||||
Finds k'th lexicographic permutation (in increasing order) of
|
Finds k'th lexicographic permutation (in increasing order) of
|
||||||
0,1,2,...n-1 in O(n^2) time.
|
0,1,2,...n-1 in O(n^2) time.
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
First permutation is always 0,1,2,...n
|
First permutation is always 0,1,2,...n
|
||||||
>>> kthPermutation(0,5)
|
>>> kthPermutation(0,5)
|
||||||
[0, 1, 2, 3, 4]
|
[0, 1, 2, 3, 4]
|
||||||
|
|
||||||
The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3],
|
The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3],
|
||||||
[0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3],
|
[0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3],
|
||||||
[1,2,3,0], [1,3,0,2]
|
[1,2,3,0], [1,3,0,2]
|
||||||
>>> kthPermutation(10,4)
|
>>> kthPermutation(10,4)
|
||||||
[1, 3, 0, 2]
|
[1, 3, 0, 2]
|
||||||
"""
|
"""
|
||||||
# Factorails from 1! to (n-1)!
|
# Factorails from 1! to (n-1)!
|
||||||
factorials = [1]
|
factorials = [1]
|
||||||
|
|
|
@ -12,8 +12,8 @@ import math as m
|
||||||
|
|
||||||
def calc_derivative(f, a, h=0.001):
|
def calc_derivative(f, a, h=0.001):
|
||||||
"""
|
"""
|
||||||
Calculates derivative at point a for function f using finite difference
|
Calculates derivative at point a for function f using finite difference
|
||||||
method
|
method
|
||||||
"""
|
"""
|
||||||
return (f(a + h) - f(a - h)) / (2 * h)
|
return (f(a + h) - f(a - h)) / (2 * h)
|
||||||
|
|
||||||
|
|
|
@ -19,9 +19,9 @@ def prime_sieve_eratosthenes(num):
|
||||||
print the prime numbers up to n
|
print the prime numbers up to n
|
||||||
|
|
||||||
>>> prime_sieve_eratosthenes(10)
|
>>> prime_sieve_eratosthenes(10)
|
||||||
2 3 5 7
|
2,3,5,7,
|
||||||
>>> prime_sieve_eratosthenes(20)
|
>>> prime_sieve_eratosthenes(20)
|
||||||
2 3 5 7 11 13 17 19
|
2,3,5,7,11,13,17,19,
|
||||||
"""
|
"""
|
||||||
|
|
||||||
primes = [True for i in range(num + 1)]
|
primes = [True for i in range(num + 1)]
|
||||||
|
@ -35,10 +35,13 @@ def prime_sieve_eratosthenes(num):
|
||||||
|
|
||||||
for prime in range(2, num + 1):
|
for prime in range(2, num + 1):
|
||||||
if primes[prime]:
|
if primes[prime]:
|
||||||
print(prime, end=" ")
|
print(prime, end=",")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
||||||
num = int(input())
|
num = int(input())
|
||||||
|
|
||||||
prime_sieve_eratosthenes(num)
|
prime_sieve_eratosthenes(num)
|
||||||
|
|
|
@ -16,20 +16,20 @@ import numpy as np
|
||||||
|
|
||||||
def relu(vector: List[float]):
|
def relu(vector: List[float]):
|
||||||
"""
|
"""
|
||||||
Implements the relu function
|
Implements the relu function
|
||||||
|
|
||||||
Parameters:
|
Parameters:
|
||||||
vector (np.array,list,tuple): A numpy array of shape (1,n)
|
vector (np.array,list,tuple): A numpy array of shape (1,n)
|
||||||
consisting of real values or a similar list,tuple
|
consisting of real values or a similar list,tuple
|
||||||
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
relu_vec (np.array): The input numpy array, after applying
|
relu_vec (np.array): The input numpy array, after applying
|
||||||
relu.
|
relu.
|
||||||
|
|
||||||
>>> vec = np.array([-1, 0, 5])
|
>>> vec = np.array([-1, 0, 5])
|
||||||
>>> relu(vec)
|
>>> relu(vec)
|
||||||
array([0, 0, 5])
|
array([0, 0, 5])
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# compare two arrays and then return element-wise maxima.
|
# compare two arrays and then return element-wise maxima.
|
||||||
|
|
|
@ -15,28 +15,28 @@ import numpy as np
|
||||||
|
|
||||||
def softmax(vector):
|
def softmax(vector):
|
||||||
"""
|
"""
|
||||||
Implements the softmax function
|
Implements the softmax function
|
||||||
|
|
||||||
Parameters:
|
Parameters:
|
||||||
vector (np.array,list,tuple): A numpy array of shape (1,n)
|
vector (np.array,list,tuple): A numpy array of shape (1,n)
|
||||||
consisting of real values or a similar list,tuple
|
consisting of real values or a similar list,tuple
|
||||||
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
softmax_vec (np.array): The input numpy array after applying
|
softmax_vec (np.array): The input numpy array after applying
|
||||||
softmax.
|
softmax.
|
||||||
|
|
||||||
The softmax vector adds up to one. We need to ceil to mitigate for
|
The softmax vector adds up to one. We need to ceil to mitigate for
|
||||||
precision
|
precision
|
||||||
>>> np.ceil(np.sum(softmax([1,2,3,4])))
|
>>> np.ceil(np.sum(softmax([1,2,3,4])))
|
||||||
1.0
|
1.0
|
||||||
|
|
||||||
>>> vec = np.array([5,5])
|
>>> vec = np.array([5,5])
|
||||||
>>> softmax(vec)
|
>>> softmax(vec)
|
||||||
array([0.5, 0.5])
|
array([0.5, 0.5])
|
||||||
|
|
||||||
>>> softmax([0])
|
>>> softmax([0])
|
||||||
array([1.])
|
array([1.])
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Calculate e^x for each x in your vector where e is Euler's
|
# Calculate e^x for each x in your vector where e is Euler's
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
def sum_of_geometric_progression(
|
def sum_of_geometric_progression(
|
||||||
first_term: int, common_ratio: int, num_of_terms: int
|
first_term: int, common_ratio: int, num_of_terms: int
|
||||||
) -> float:
|
) -> float:
|
||||||
""""
|
""" "
|
||||||
Return the sum of n terms in a geometric progression.
|
Return the sum of n terms in a geometric progression.
|
||||||
>>> sum_of_geometric_progression(1, 2, 10)
|
>>> sum_of_geometric_progression(1, 2, 10)
|
||||||
1023.0
|
1023.0
|
||||||
|
|
|
@ -63,8 +63,7 @@ def zeller(date_input: str) -> str:
|
||||||
>>> zeller('01-31-19082939')
|
>>> zeller('01-31-19082939')
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
ValueError: Must be 10 characters long
|
ValueError: Must be 10 characters long"""
|
||||||
"""
|
|
||||||
|
|
||||||
# Days of the week for response
|
# Days of the week for response
|
||||||
days = {
|
days = {
|
||||||
|
|
|
@ -168,7 +168,9 @@ def main():
|
||||||
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
|
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
|
||||||
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
|
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
|
||||||
print(f"Add Operation, {add(matrix_a, matrix_b) = } \n")
|
print(f"Add Operation, {add(matrix_a, matrix_b) = } \n")
|
||||||
print(f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n",)
|
print(
|
||||||
|
f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n",
|
||||||
|
)
|
||||||
print(f"Identity: {identity(5)}\n")
|
print(f"Identity: {identity(5)}\n")
|
||||||
print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")
|
print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")
|
||||||
print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n")
|
print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n")
|
||||||
|
|
|
@ -16,14 +16,14 @@ def printMaxActivities(start, finish):
|
||||||
>>> finish = [2, 4, 6, 7, 9, 9]
|
>>> finish = [2, 4, 6, 7, 9, 9]
|
||||||
>>> printMaxActivities(start, finish)
|
>>> printMaxActivities(start, finish)
|
||||||
The following activities are selected:
|
The following activities are selected:
|
||||||
0 1 3 4
|
0,1,3,4,
|
||||||
"""
|
"""
|
||||||
n = len(finish)
|
n = len(finish)
|
||||||
print("The following activities are selected:")
|
print("The following activities are selected:")
|
||||||
|
|
||||||
# The first activity is always selected
|
# The first activity is always selected
|
||||||
i = 0
|
i = 0
|
||||||
print(i, end=" ")
|
print(i, end=",")
|
||||||
|
|
||||||
# Consider rest of the activities
|
# Consider rest of the activities
|
||||||
for j in range(n):
|
for j in range(n):
|
||||||
|
@ -32,16 +32,15 @@ def printMaxActivities(start, finish):
|
||||||
# or equal to the finish time of previously
|
# or equal to the finish time of previously
|
||||||
# selected activity, then select it
|
# selected activity, then select it
|
||||||
if start[j] >= finish[i]:
|
if start[j] >= finish[i]:
|
||||||
print(j, end=" ")
|
print(j, end=",")
|
||||||
i = j
|
i = j
|
||||||
|
|
||||||
|
|
||||||
# Driver program to test above function
|
if __name__ == "__main__":
|
||||||
start = [1, 3, 0, 5, 8, 5]
|
import doctest
|
||||||
finish = [2, 4, 6, 7, 9, 9]
|
|
||||||
printMaxActivities(start, finish)
|
|
||||||
|
|
||||||
"""
|
doctest.testmod()
|
||||||
The following activities are selected:
|
|
||||||
0 1 3 4
|
start = [1, 3, 0, 5, 8, 5]
|
||||||
"""
|
finish = [2, 4, 6, 7, 9, 9]
|
||||||
|
printMaxActivities(start, finish)
|
||||||
|
|
|
@ -52,7 +52,7 @@ def seed(canvas):
|
||||||
|
|
||||||
|
|
||||||
def run(canvas):
|
def run(canvas):
|
||||||
""" This function runs the rules of game through all points, and changes their
|
"""This function runs the rules of game through all points, and changes their
|
||||||
status accordingly.(in the same canvas)
|
status accordingly.(in the same canvas)
|
||||||
@Args:
|
@Args:
|
||||||
--
|
--
|
||||||
|
|
|
@ -12,7 +12,7 @@ class LRUCache:
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def __init__(self, n: int):
|
def __init__(self, n: int):
|
||||||
""" Creates an empty store and map for the keys.
|
"""Creates an empty store and map for the keys.
|
||||||
The LRUCache is set the size n.
|
The LRUCache is set the size n.
|
||||||
"""
|
"""
|
||||||
self.dq_store = deque()
|
self.dq_store = deque()
|
||||||
|
@ -26,9 +26,9 @@ class LRUCache:
|
||||||
|
|
||||||
def refer(self, x):
|
def refer(self, x):
|
||||||
"""
|
"""
|
||||||
Looks for a page in the cache store and adds reference to the set.
|
Looks for a page in the cache store and adds reference to the set.
|
||||||
Remove the least recently used key if the store is full.
|
Remove the least recently used key if the store is full.
|
||||||
Update store to reflect recent access.
|
Update store to reflect recent access.
|
||||||
"""
|
"""
|
||||||
if x not in self.key_reference_map:
|
if x not in self.key_reference_map:
|
||||||
if len(self.dq_store) == LRUCache._MAX_CAPACITY:
|
if len(self.dq_store) == LRUCache._MAX_CAPACITY:
|
||||||
|
@ -47,7 +47,7 @@ class LRUCache:
|
||||||
|
|
||||||
def display(self):
|
def display(self):
|
||||||
"""
|
"""
|
||||||
Prints all the elements in the store.
|
Prints all the elements in the store.
|
||||||
"""
|
"""
|
||||||
for k in self.dq_store:
|
for k in self.dq_store:
|
||||||
print(k)
|
print(k)
|
||||||
|
|
|
@ -6,7 +6,7 @@ def floyd(n):
|
||||||
"""
|
"""
|
||||||
Parameters:
|
Parameters:
|
||||||
n : size of pattern
|
n : size of pattern
|
||||||
"""
|
"""
|
||||||
for i in range(0, n):
|
for i in range(0, n):
|
||||||
for j in range(0, n - i - 1): # printing spaces
|
for j in range(0, n - i - 1): # printing spaces
|
||||||
print(" ", end="")
|
print(" ", end="")
|
||||||
|
@ -20,7 +20,7 @@ def reverse_floyd(n):
|
||||||
"""
|
"""
|
||||||
Parameters:
|
Parameters:
|
||||||
n : size of pattern
|
n : size of pattern
|
||||||
"""
|
"""
|
||||||
for i in range(n, 0, -1):
|
for i in range(n, 0, -1):
|
||||||
for j in range(i, 0, -1): # printing stars
|
for j in range(i, 0, -1): # printing stars
|
||||||
print("* ", end="")
|
print("* ", end="")
|
||||||
|
@ -34,7 +34,7 @@ def pretty_print(n):
|
||||||
"""
|
"""
|
||||||
Parameters:
|
Parameters:
|
||||||
n : size of pattern
|
n : size of pattern
|
||||||
"""
|
"""
|
||||||
if n <= 0:
|
if n <= 0:
|
||||||
print(" ... .... nothing printing :(")
|
print(" ... .... nothing printing :(")
|
||||||
return
|
return
|
||||||
|
|
|
@ -43,8 +43,8 @@ from math import sqrt
|
||||||
|
|
||||||
def isPrime(number):
|
def isPrime(number):
|
||||||
"""
|
"""
|
||||||
input: positive integer 'number'
|
input: positive integer 'number'
|
||||||
returns true if 'number' is prime otherwise false.
|
returns true if 'number' is prime otherwise false.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -77,11 +77,11 @@ def isPrime(number):
|
||||||
|
|
||||||
def sieveEr(N):
|
def sieveEr(N):
|
||||||
"""
|
"""
|
||||||
input: positive integer 'N' > 2
|
input: positive integer 'N' > 2
|
||||||
returns a list of prime numbers from 2 up to N.
|
returns a list of prime numbers from 2 up to N.
|
||||||
|
|
||||||
This function implements the algorithm called
|
This function implements the algorithm called
|
||||||
sieve of erathostenes.
|
sieve of erathostenes.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
@ -115,9 +115,9 @@ def sieveEr(N):
|
||||||
|
|
||||||
def getPrimeNumbers(N):
|
def getPrimeNumbers(N):
|
||||||
"""
|
"""
|
||||||
input: positive integer 'N' > 2
|
input: positive integer 'N' > 2
|
||||||
returns a list of prime numbers from 2 up to N (inclusive)
|
returns a list of prime numbers from 2 up to N (inclusive)
|
||||||
This function is more efficient as function 'sieveEr(...)'
|
This function is more efficient as function 'sieveEr(...)'
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -144,8 +144,8 @@ def getPrimeNumbers(N):
|
||||||
|
|
||||||
def primeFactorization(number):
|
def primeFactorization(number):
|
||||||
"""
|
"""
|
||||||
input: positive integer 'number'
|
input: positive integer 'number'
|
||||||
returns a list of the prime number factors of 'number'
|
returns a list of the prime number factors of 'number'
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -188,8 +188,8 @@ def primeFactorization(number):
|
||||||
|
|
||||||
def greatestPrimeFactor(number):
|
def greatestPrimeFactor(number):
|
||||||
"""
|
"""
|
||||||
input: positive integer 'number' >= 0
|
input: positive integer 'number' >= 0
|
||||||
returns the greatest prime number factor of 'number'
|
returns the greatest prime number factor of 'number'
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -215,8 +215,8 @@ def greatestPrimeFactor(number):
|
||||||
|
|
||||||
def smallestPrimeFactor(number):
|
def smallestPrimeFactor(number):
|
||||||
"""
|
"""
|
||||||
input: integer 'number' >= 0
|
input: integer 'number' >= 0
|
||||||
returns the smallest prime number factor of 'number'
|
returns the smallest prime number factor of 'number'
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -242,8 +242,8 @@ def smallestPrimeFactor(number):
|
||||||
|
|
||||||
def isEven(number):
|
def isEven(number):
|
||||||
"""
|
"""
|
||||||
input: integer 'number'
|
input: integer 'number'
|
||||||
returns true if 'number' is even, otherwise false.
|
returns true if 'number' is even, otherwise false.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -258,8 +258,8 @@ def isEven(number):
|
||||||
|
|
||||||
def isOdd(number):
|
def isOdd(number):
|
||||||
"""
|
"""
|
||||||
input: integer 'number'
|
input: integer 'number'
|
||||||
returns true if 'number' is odd, otherwise false.
|
returns true if 'number' is odd, otherwise false.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -274,9 +274,9 @@ def isOdd(number):
|
||||||
|
|
||||||
def goldbach(number):
|
def goldbach(number):
|
||||||
"""
|
"""
|
||||||
Goldbach's assumption
|
Goldbach's assumption
|
||||||
input: a even positive integer 'number' > 2
|
input: a even positive integer 'number' > 2
|
||||||
returns a list of two prime numbers whose sum is equal to 'number'
|
returns a list of two prime numbers whose sum is equal to 'number'
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -329,9 +329,9 @@ def goldbach(number):
|
||||||
|
|
||||||
def gcd(number1, number2):
|
def gcd(number1, number2):
|
||||||
"""
|
"""
|
||||||
Greatest common divisor
|
Greatest common divisor
|
||||||
input: two positive integer 'number1' and 'number2'
|
input: two positive integer 'number1' and 'number2'
|
||||||
returns the greatest common divisor of 'number1' and 'number2'
|
returns the greatest common divisor of 'number1' and 'number2'
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -363,9 +363,9 @@ def gcd(number1, number2):
|
||||||
|
|
||||||
def kgV(number1, number2):
|
def kgV(number1, number2):
|
||||||
"""
|
"""
|
||||||
Least common multiple
|
Least common multiple
|
||||||
input: two positive integer 'number1' and 'number2'
|
input: two positive integer 'number1' and 'number2'
|
||||||
returns the least common multiple of 'number1' and 'number2'
|
returns the least common multiple of 'number1' and 'number2'
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -443,9 +443,9 @@ def kgV(number1, number2):
|
||||||
|
|
||||||
def getPrime(n):
|
def getPrime(n):
|
||||||
"""
|
"""
|
||||||
Gets the n-th prime number.
|
Gets the n-th prime number.
|
||||||
input: positive integer 'n' >= 0
|
input: positive integer 'n' >= 0
|
||||||
returns the n-th prime number, beginning at index 0
|
returns the n-th prime number, beginning at index 0
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -478,10 +478,10 @@ def getPrime(n):
|
||||||
|
|
||||||
def getPrimesBetween(pNumber1, pNumber2):
|
def getPrimesBetween(pNumber1, pNumber2):
|
||||||
"""
|
"""
|
||||||
input: prime numbers 'pNumber1' and 'pNumber2'
|
input: prime numbers 'pNumber1' and 'pNumber2'
|
||||||
pNumber1 < pNumber2
|
pNumber1 < pNumber2
|
||||||
returns a list of all prime numbers between 'pNumber1' (exclusive)
|
returns a list of all prime numbers between 'pNumber1' (exclusive)
|
||||||
and 'pNumber2' (exclusive)
|
and 'pNumber2' (exclusive)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -522,8 +522,8 @@ def getPrimesBetween(pNumber1, pNumber2):
|
||||||
|
|
||||||
def getDivisors(n):
|
def getDivisors(n):
|
||||||
"""
|
"""
|
||||||
input: positive integer 'n' >= 1
|
input: positive integer 'n' >= 1
|
||||||
returns all divisors of n (inclusive 1 and 'n')
|
returns all divisors of n (inclusive 1 and 'n')
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -547,8 +547,8 @@ def getDivisors(n):
|
||||||
|
|
||||||
def isPerfectNumber(number):
|
def isPerfectNumber(number):
|
||||||
"""
|
"""
|
||||||
input: positive integer 'number' > 1
|
input: positive integer 'number' > 1
|
||||||
returns true if 'number' is a perfect number otherwise false.
|
returns true if 'number' is a perfect number otherwise false.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -574,9 +574,9 @@ def isPerfectNumber(number):
|
||||||
|
|
||||||
def simplifyFraction(numerator, denominator):
|
def simplifyFraction(numerator, denominator):
|
||||||
"""
|
"""
|
||||||
input: two integer 'numerator' and 'denominator'
|
input: two integer 'numerator' and 'denominator'
|
||||||
assumes: 'denominator' != 0
|
assumes: 'denominator' != 0
|
||||||
returns: a tuple with simplify numerator and denominator.
|
returns: a tuple with simplify numerator and denominator.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -604,8 +604,8 @@ def simplifyFraction(numerator, denominator):
|
||||||
|
|
||||||
def factorial(n):
|
def factorial(n):
|
||||||
"""
|
"""
|
||||||
input: positive integer 'n'
|
input: positive integer 'n'
|
||||||
returns the factorial of 'n' (n!)
|
returns the factorial of 'n' (n!)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
@ -624,8 +624,8 @@ def factorial(n):
|
||||||
|
|
||||||
def fib(n):
|
def fib(n):
|
||||||
"""
|
"""
|
||||||
input: positive integer 'n'
|
input: positive integer 'n'
|
||||||
returns the n-th fibonacci term , indexing by 0
|
returns the n-th fibonacci term , indexing by 0
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# precondition
|
# precondition
|
||||||
|
|
|
@ -23,8 +23,7 @@ def solution(n):
|
||||||
product = -1
|
product = -1
|
||||||
d = 0
|
d = 0
|
||||||
for a in range(1, n // 3):
|
for a in range(1, n // 3):
|
||||||
"""Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c
|
"""Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c"""
|
||||||
"""
|
|
||||||
b = (n * n - 2 * a * n) // (2 * n - 2 * a)
|
b = (n * n - 2 * a * n) // (2 * n - 2 * a)
|
||||||
c = n - a - b
|
c = n - a - b
|
||||||
if c * c == (a * a + b * b):
|
if c * c == (a * a + b * b):
|
||||||
|
|
|
@ -12,7 +12,7 @@ smaller than n when n is smaller than 10 million. Only for positive numbers.
|
||||||
|
|
||||||
|
|
||||||
def prime_sum(n: int) -> int:
|
def prime_sum(n: int) -> int:
|
||||||
""" Returns the sum of all the primes below n.
|
"""Returns the sum of all the primes below n.
|
||||||
|
|
||||||
>>> prime_sum(2_000_000)
|
>>> prime_sum(2_000_000)
|
||||||
142913828922
|
142913828922
|
||||||
|
|
|
@ -8,31 +8,31 @@ from math import factorial
|
||||||
|
|
||||||
def lattice_paths(n):
|
def lattice_paths(n):
|
||||||
"""
|
"""
|
||||||
Returns the number of paths possible in a n x n grid starting at top left
|
Returns the number of paths possible in a n x n grid starting at top left
|
||||||
corner going to bottom right corner and being able to move right and down
|
corner going to bottom right corner and being able to move right and down
|
||||||
only.
|
only.
|
||||||
|
|
||||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 50
|
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 50
|
||||||
1.008913445455642e+29
|
1.008913445455642e+29
|
||||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 25
|
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 25
|
||||||
126410606437752.0
|
126410606437752.0
|
||||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 23
|
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 23
|
||||||
8233430727600.0
|
8233430727600.0
|
||||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 15
|
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 15
|
||||||
155117520.0
|
155117520.0
|
||||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 1
|
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 1
|
||||||
2.0
|
2.0
|
||||||
|
|
||||||
>>> lattice_paths(25)
|
>>> lattice_paths(25)
|
||||||
126410606437752
|
126410606437752
|
||||||
>>> lattice_paths(23)
|
>>> lattice_paths(23)
|
||||||
8233430727600
|
8233430727600
|
||||||
>>> lattice_paths(20)
|
>>> lattice_paths(20)
|
||||||
137846528820
|
137846528820
|
||||||
>>> lattice_paths(15)
|
>>> lattice_paths(15)
|
||||||
155117520
|
155117520
|
||||||
>>> lattice_paths(1)
|
>>> lattice_paths(1)
|
||||||
2
|
2
|
||||||
|
|
||||||
"""
|
"""
|
||||||
n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
|
n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
|
||||||
|
|
|
@ -39,17 +39,17 @@ def is_prime(k: int) -> bool:
|
||||||
|
|
||||||
def solution(a_limit: int, b_limit: int) -> int:
|
def solution(a_limit: int, b_limit: int) -> int:
|
||||||
"""
|
"""
|
||||||
>>> solution(1000, 1000)
|
>>> solution(1000, 1000)
|
||||||
-59231
|
-59231
|
||||||
>>> solution(200, 1000)
|
>>> solution(200, 1000)
|
||||||
-59231
|
-59231
|
||||||
>>> solution(200, 200)
|
>>> solution(200, 200)
|
||||||
-4925
|
-4925
|
||||||
>>> solution(-1000, 1000)
|
>>> solution(-1000, 1000)
|
||||||
0
|
0
|
||||||
>>> solution(-1000, -1000)
|
>>> solution(-1000, -1000)
|
||||||
0
|
0
|
||||||
"""
|
"""
|
||||||
longest = [0, 0, 0] # length, a, b
|
longest = [0, 0, 0] # length, a, b
|
||||||
for a in range((a_limit * -1) + 1, a_limit):
|
for a in range((a_limit * -1) + 1, a_limit):
|
||||||
for b in range(2, b_limit):
|
for b in range(2, b_limit):
|
||||||
|
|
|
@ -1,18 +1,18 @@
|
||||||
def maximum_digital_sum(a: int, b: int) -> int:
|
def maximum_digital_sum(a: int, b: int) -> int:
|
||||||
"""
|
"""
|
||||||
Considering natural numbers of the form, a**b, where a, b < 100,
|
Considering natural numbers of the form, a**b, where a, b < 100,
|
||||||
what is the maximum digital sum?
|
what is the maximum digital sum?
|
||||||
:param a:
|
:param a:
|
||||||
:param b:
|
:param b:
|
||||||
:return:
|
:return:
|
||||||
>>> maximum_digital_sum(10,10)
|
>>> maximum_digital_sum(10,10)
|
||||||
45
|
45
|
||||||
|
|
||||||
>>> maximum_digital_sum(100,100)
|
>>> maximum_digital_sum(100,100)
|
||||||
972
|
972
|
||||||
|
|
||||||
>>> maximum_digital_sum(100,200)
|
>>> maximum_digital_sum(100,200)
|
||||||
1872
|
1872
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of
|
# RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of
|
||||||
|
|
|
@ -29,11 +29,13 @@ def merge_sort(collection: list) -> list:
|
||||||
:param right: right collection
|
:param right: right collection
|
||||||
:return: merge result
|
:return: merge result
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def _merge():
|
def _merge():
|
||||||
while left and right:
|
while left and right:
|
||||||
yield (left if left[0] <= right[0] else right).pop(0)
|
yield (left if left[0] <= right[0] else right).pop(0)
|
||||||
yield from left
|
yield from left
|
||||||
yield from right
|
yield from right
|
||||||
|
|
||||||
return list(_merge())
|
return list(_merge())
|
||||||
|
|
||||||
if len(collection) <= 1:
|
if len(collection) <= 1:
|
||||||
|
@ -44,6 +46,7 @@ def merge_sort(collection: list) -> list:
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import doctest
|
import doctest
|
||||||
|
|
||||||
doctest.testmod()
|
doctest.testmod()
|
||||||
user_input = input("Enter numbers separated by a comma:\n").strip()
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
||||||
unsorted = [int(item) for item in user_input.split(",")]
|
unsorted = [int(item) for item in user_input.split(",")]
|
||||||
|
|
|
@ -1,41 +1,42 @@
|
||||||
def bubble_sort(list1):
|
def bubble_sort(list_data: list, length: int = 0) -> list:
|
||||||
"""
|
"""
|
||||||
It is similar is bubble sort but recursive.
|
It is similar is bubble sort but recursive.
|
||||||
:param list1: mutable ordered sequence of elements
|
:param list_data: mutable ordered sequence of elements
|
||||||
|
:param length: length of list data
|
||||||
:return: the same list in ascending order
|
:return: the same list in ascending order
|
||||||
|
|
||||||
>>> bubble_sort([0, 5, 2, 3, 2])
|
>>> bubble_sort([0, 5, 2, 3, 2], 5)
|
||||||
[0, 2, 2, 3, 5]
|
[0, 2, 2, 3, 5]
|
||||||
|
|
||||||
>>> bubble_sort([])
|
>>> bubble_sort([], 0)
|
||||||
[]
|
[]
|
||||||
|
|
||||||
>>> bubble_sort([-2, -45, -5])
|
>>> bubble_sort([-2, -45, -5], 3)
|
||||||
[-45, -5, -2]
|
[-45, -5, -2]
|
||||||
|
|
||||||
>>> bubble_sort([-23, 0, 6, -4, 34])
|
>>> bubble_sort([-23, 0, 6, -4, 34], 5)
|
||||||
[-23, -4, 0, 6, 34]
|
[-23, -4, 0, 6, 34]
|
||||||
|
|
||||||
>>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34])
|
>>> bubble_sort([-23, 0, 6, -4, 34], 5) == sorted([-23, 0, 6, -4, 34])
|
||||||
True
|
True
|
||||||
|
|
||||||
>>> bubble_sort(['z','a','y','b','x','c'])
|
>>> bubble_sort(['z','a','y','b','x','c'], 6)
|
||||||
['a', 'b', 'c', 'x', 'y', 'z']
|
['a', 'b', 'c', 'x', 'y', 'z']
|
||||||
|
|
||||||
|
>>> bubble_sort([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6])
|
||||||
|
[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
|
||||||
"""
|
"""
|
||||||
|
length = length or len(list_data)
|
||||||
|
swapped = False
|
||||||
|
for i in range(length - 1):
|
||||||
|
if list_data[i] > list_data[i + 1]:
|
||||||
|
list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i]
|
||||||
|
swapped = True
|
||||||
|
|
||||||
for i, num in enumerate(list1):
|
return list_data if not swapped else bubble_sort(list_data, length - 1)
|
||||||
try:
|
|
||||||
if list1[i + 1] < num:
|
|
||||||
list1[i] = list1[i + 1]
|
|
||||||
list1[i + 1] = num
|
|
||||||
bubble_sort(list1)
|
|
||||||
except IndexError:
|
|
||||||
pass
|
|
||||||
return list1
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
list1 = [33, 99, 22, 11, 66]
|
import doctest
|
||||||
bubble_sort(list1)
|
|
||||||
print(list1)
|
doctest.testmod()
|
||||||
|
|
|
@ -25,7 +25,7 @@ class BoyerMooreSearch:
|
||||||
self.textLen, self.patLen = len(text), len(pattern)
|
self.textLen, self.patLen = len(text), len(pattern)
|
||||||
|
|
||||||
def match_in_pattern(self, char):
|
def match_in_pattern(self, char):
|
||||||
""" finds the index of char in pattern in reverse order
|
"""finds the index of char in pattern in reverse order
|
||||||
|
|
||||||
Parameters :
|
Parameters :
|
||||||
char (chr): character to be searched
|
char (chr): character to be searched
|
||||||
|
|
|
@ -16,7 +16,7 @@ def capitalize(sentence: str) -> str:
|
||||||
''
|
''
|
||||||
"""
|
"""
|
||||||
if not sentence:
|
if not sentence:
|
||||||
return ''
|
return ""
|
||||||
lower_to_upper = {lc: uc for lc, uc in zip(ascii_lowercase, ascii_uppercase)}
|
lower_to_upper = {lc: uc for lc, uc in zip(ascii_lowercase, ascii_uppercase)}
|
||||||
return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:]
|
return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:]
|
||||||
|
|
||||||
|
|
|
@ -53,11 +53,11 @@ def pre_order(node: TreeNode) -> None:
|
||||||
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
||||||
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
||||||
>>> pre_order(root)
|
>>> pre_order(root)
|
||||||
1 2 4 5 3 6 7
|
1,2,4,5,3,6,7,
|
||||||
"""
|
"""
|
||||||
if not isinstance(node, TreeNode) or not node:
|
if not isinstance(node, TreeNode) or not node:
|
||||||
return
|
return
|
||||||
print(node.data, end=" ")
|
print(node.data, end=",")
|
||||||
pre_order(node.left)
|
pre_order(node.left)
|
||||||
pre_order(node.right)
|
pre_order(node.right)
|
||||||
|
|
||||||
|
@ -75,12 +75,12 @@ def in_order(node: TreeNode) -> None:
|
||||||
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
||||||
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
||||||
>>> in_order(root)
|
>>> in_order(root)
|
||||||
4 2 5 1 6 3 7
|
4,2,5,1,6,3,7,
|
||||||
"""
|
"""
|
||||||
if not isinstance(node, TreeNode) or not node:
|
if not isinstance(node, TreeNode) or not node:
|
||||||
return
|
return
|
||||||
in_order(node.left)
|
in_order(node.left)
|
||||||
print(node.data, end=" ")
|
print(node.data, end=",")
|
||||||
in_order(node.right)
|
in_order(node.right)
|
||||||
|
|
||||||
|
|
||||||
|
@ -97,13 +97,13 @@ def post_order(node: TreeNode) -> None:
|
||||||
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
||||||
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
||||||
>>> post_order(root)
|
>>> post_order(root)
|
||||||
4 5 2 6 7 3 1
|
4,5,2,6,7,3,1,
|
||||||
"""
|
"""
|
||||||
if not isinstance(node, TreeNode) or not node:
|
if not isinstance(node, TreeNode) or not node:
|
||||||
return
|
return
|
||||||
post_order(node.left)
|
post_order(node.left)
|
||||||
post_order(node.right)
|
post_order(node.right)
|
||||||
print(node.data, end=" ")
|
print(node.data, end=",")
|
||||||
|
|
||||||
|
|
||||||
def level_order(node: TreeNode) -> None:
|
def level_order(node: TreeNode) -> None:
|
||||||
|
@ -119,7 +119,7 @@ def level_order(node: TreeNode) -> None:
|
||||||
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
||||||
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
||||||
>>> level_order(root)
|
>>> level_order(root)
|
||||||
1 2 3 4 5 6 7
|
1,2,3,4,5,6,7,
|
||||||
"""
|
"""
|
||||||
if not isinstance(node, TreeNode) or not node:
|
if not isinstance(node, TreeNode) or not node:
|
||||||
return
|
return
|
||||||
|
@ -127,7 +127,7 @@ def level_order(node: TreeNode) -> None:
|
||||||
q.put(node)
|
q.put(node)
|
||||||
while not q.empty():
|
while not q.empty():
|
||||||
node_dequeued = q.get()
|
node_dequeued = q.get()
|
||||||
print(node_dequeued.data, end=" ")
|
print(node_dequeued.data, end=",")
|
||||||
if node_dequeued.left:
|
if node_dequeued.left:
|
||||||
q.put(node_dequeued.left)
|
q.put(node_dequeued.left)
|
||||||
if node_dequeued.right:
|
if node_dequeued.right:
|
||||||
|
@ -146,10 +146,10 @@ def level_order_actual(node: TreeNode) -> None:
|
||||||
>>> root.left, root.right = tree_node2, tree_node3
|
>>> root.left, root.right = tree_node2, tree_node3
|
||||||
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
||||||
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
||||||
>>> level_order_actual(root)
|
>>> level_order_actual(root)
|
||||||
1
|
1,
|
||||||
2 3
|
2,3,
|
||||||
4 5 6 7
|
4,5,6,7,
|
||||||
"""
|
"""
|
||||||
if not isinstance(node, TreeNode) or not node:
|
if not isinstance(node, TreeNode) or not node:
|
||||||
return
|
return
|
||||||
|
@ -159,7 +159,7 @@ def level_order_actual(node: TreeNode) -> None:
|
||||||
list = []
|
list = []
|
||||||
while not q.empty():
|
while not q.empty():
|
||||||
node_dequeued = q.get()
|
node_dequeued = q.get()
|
||||||
print(node_dequeued.data, end=" ")
|
print(node_dequeued.data, end=",")
|
||||||
if node_dequeued.left:
|
if node_dequeued.left:
|
||||||
list.append(node_dequeued.left)
|
list.append(node_dequeued.left)
|
||||||
if node_dequeued.right:
|
if node_dequeued.right:
|
||||||
|
@ -183,7 +183,7 @@ def pre_order_iter(node: TreeNode) -> None:
|
||||||
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
||||||
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
||||||
>>> pre_order_iter(root)
|
>>> pre_order_iter(root)
|
||||||
1 2 4 5 3 6 7
|
1,2,4,5,3,6,7,
|
||||||
"""
|
"""
|
||||||
if not isinstance(node, TreeNode) or not node:
|
if not isinstance(node, TreeNode) or not node:
|
||||||
return
|
return
|
||||||
|
@ -191,7 +191,7 @@ def pre_order_iter(node: TreeNode) -> None:
|
||||||
n = node
|
n = node
|
||||||
while n or stack:
|
while n or stack:
|
||||||
while n: # start from root node, find its left child
|
while n: # start from root node, find its left child
|
||||||
print(n.data, end=" ")
|
print(n.data, end=",")
|
||||||
stack.append(n)
|
stack.append(n)
|
||||||
n = n.left
|
n = n.left
|
||||||
# end of while means current node doesn't have left child
|
# end of while means current node doesn't have left child
|
||||||
|
@ -213,7 +213,7 @@ def in_order_iter(node: TreeNode) -> None:
|
||||||
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
||||||
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
||||||
>>> in_order_iter(root)
|
>>> in_order_iter(root)
|
||||||
4 2 5 1 6 3 7
|
4,2,5,1,6,3,7,
|
||||||
"""
|
"""
|
||||||
if not isinstance(node, TreeNode) or not node:
|
if not isinstance(node, TreeNode) or not node:
|
||||||
return
|
return
|
||||||
|
@ -224,7 +224,7 @@ def in_order_iter(node: TreeNode) -> None:
|
||||||
stack.append(n)
|
stack.append(n)
|
||||||
n = n.left
|
n = n.left
|
||||||
n = stack.pop()
|
n = stack.pop()
|
||||||
print(n.data, end=" ")
|
print(n.data, end=",")
|
||||||
n = n.right
|
n = n.right
|
||||||
|
|
||||||
|
|
||||||
|
@ -241,7 +241,7 @@ def post_order_iter(node: TreeNode) -> None:
|
||||||
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
|
||||||
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
|
||||||
>>> post_order_iter(root)
|
>>> post_order_iter(root)
|
||||||
4 5 2 6 7 3 1
|
4,5,2,6,7,3,1,
|
||||||
"""
|
"""
|
||||||
if not isinstance(node, TreeNode) or not node:
|
if not isinstance(node, TreeNode) or not node:
|
||||||
return
|
return
|
||||||
|
@ -256,7 +256,7 @@ def post_order_iter(node: TreeNode) -> None:
|
||||||
stack1.append(n.right)
|
stack1.append(n.right)
|
||||||
stack2.append(n)
|
stack2.append(n)
|
||||||
while stack2: # pop up from stack2 will be the post order
|
while stack2: # pop up from stack2 will be the post order
|
||||||
print(stack2.pop().data, end=" ")
|
print(stack2.pop().data, end=",")
|
||||||
|
|
||||||
|
|
||||||
def prompt(s: str = "", width=50, char="*") -> str:
|
def prompt(s: str = "", width=50, char="*") -> str:
|
||||||
|
|
Loading…
Reference in New Issue
Block a user