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
|
||||||
|
|
|
@ -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))
|
||||||
|
|
|
@ -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
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -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.
|
||||||
|
|
|
@ -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
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -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):
|
||||||
|
|
|
@ -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)
|
||||||
|
|
|
@ -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__":
|
||||||
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
||||||
|
|
||||||
start = [1, 3, 0, 5, 8, 5]
|
start = [1, 3, 0, 5, 8, 5]
|
||||||
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:
|
|
||||||
0 1 3 4
|
|
||||||
"""
|
|
||||||
|
|
|
@ -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):
|
||||||
|
|
|
@ -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()
|
||||||
|
|
|
@ -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:
|
||||||
|
@ -147,9 +147,9 @@ def level_order_actual(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_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