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:
Du Yuanchao 2020-09-10 16:31:26 +08:00 committed by GitHub
parent 25946e4570
commit 4d0a8f2355
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
60 changed files with 900 additions and 859 deletions

View File

@ -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)
def newton(function: RealFunc, derivative: RealFunc, starting_int: int,) -> float:
def newton(
function: RealFunc,
derivative: RealFunc,
starting_int: int,
) -> float:
"""
>>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3)
2.0945514815423474

View File

@ -17,26 +17,50 @@ Created by TrapinchO
# used alphabet --------------------------
# from string.ascii_uppercase
abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# -------------------------- default selection --------------------------
# rotors --------------------------
rotor1 = 'EGZWVONAHDCLFQMSIPJBYUKXTR'
rotor2 = 'FOBHMDKEXQNRAULPGSJVTYICZW'
rotor3 = 'ZJXESIUQLHAVRMDOYGTNFWPBKC'
rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR"
rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW"
rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC"
# reflector --------------------------
reflector = {'A': 'N', 'N': 'A', 'B': 'O', 'O': 'B', 'C': 'P', 'P': 'C', 'D': 'Q',
'Q': 'D', 'E': 'R', 'R': 'E', 'F': 'S', 'S': 'F', 'G': 'T', 'T': 'G',
'H': 'U', 'U': 'H', 'I': 'V', 'V': 'I', 'J': 'W', 'W': 'J', 'K': 'X',
'X': 'K', 'L': 'Y', 'Y': 'L', 'M': 'Z', 'Z': 'M'}
reflector = {
"A": "N",
"N": "A",
"B": "O",
"O": "B",
"C": "P",
"P": "C",
"D": "Q",
"Q": "D",
"E": "R",
"R": "E",
"F": "S",
"S": "F",
"G": "T",
"T": "G",
"H": "U",
"U": "H",
"I": "V",
"V": "I",
"J": "W",
"W": "J",
"K": "X",
"X": "K",
"L": "Y",
"Y": "L",
"M": "Z",
"Z": "M",
}
# -------------------------- extra rotors --------------------------
rotor4 = 'RMDJXFUWGISLHVTCQNKYPBEZOA'
rotor5 = 'SGLCPQWZHKXAREONTFBVIYJUDM'
rotor6 = 'HVSICLTYKQUBXDWAJZOMFGPREN'
rotor7 = 'RZWQHFMVDBKICJLNTUXAGYPSOE'
rotor8 = 'LFKIJODBEGAMQPXVUHYSTCZRWN'
rotor9 = 'KOAEGVDHXPQZMLFTYWJNBRCIUS'
rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA"
rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM"
rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN"
rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE"
rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN"
rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS"
def _validator(rotpos: tuple, rotsel: tuple, pb: str) -> tuple:
@ -57,19 +81,22 @@ def _validator(rotpos: tuple, rotsel: tuple, pb: str) -> tuple:
unique_rotsel = len(set(rotsel))
if unique_rotsel < 3:
raise Exception(f'Please use 3 unique rotors (not {unique_rotsel})')
raise Exception(f"Please use 3 unique rotors (not {unique_rotsel})")
# Checks if rotor positions are valid
rotorpos1, rotorpos2, rotorpos3 = rotpos
if not 0 < rotorpos1 <= len(abc):
raise ValueError(f'First rotor position is not within range of 1..26 ('
f'{rotorpos1}')
raise ValueError(
f"First rotor position is not within range of 1..26 (" f"{rotorpos1}"
)
if not 0 < rotorpos2 <= len(abc):
raise ValueError(f'Second rotor position is not within range of 1..26 ('
f'{rotorpos2})')
raise ValueError(
f"Second rotor position is not within range of 1..26 (" f"{rotorpos2})"
)
if not 0 < rotorpos3 <= len(abc):
raise ValueError(f'Third rotor position is not within range of 1..26 ('
f'{rotorpos3})')
raise ValueError(
f"Third rotor position is not within range of 1..26 (" f"{rotorpos3})"
)
# Validates string and returns dict
pb = _plugboard(pb)
@ -97,21 +124,21 @@ def _plugboard(pbstring: str) -> dict:
# a) is type string
# b) has even length (so pairs can be made)
if not isinstance(pbstring, str):
raise TypeError(f'Plugboard setting isn\'t type string ({type(pbstring)})')
raise TypeError(f"Plugboard setting isn't type string ({type(pbstring)})")
elif len(pbstring) % 2 != 0:
raise Exception(f'Odd number of symbols ({len(pbstring)})')
elif pbstring == '':
raise Exception(f"Odd number of symbols ({len(pbstring)})")
elif pbstring == "":
return {}
pbstring.replace(' ', '')
pbstring.replace(" ", "")
# Checks if all characters are unique
tmppbl = set()
for i in pbstring:
if i not in abc:
raise Exception(f'\'{i}\' not in list of symbols')
raise Exception(f"'{i}' not in list of symbols")
elif i in tmppbl:
raise Exception(f'Duplicate symbol ({i})')
raise Exception(f"Duplicate symbol ({i})")
else:
tmppbl.add(i)
del tmppbl
@ -125,8 +152,12 @@ def _plugboard(pbstring: str) -> dict:
return pb
def enigma(text: str, rotor_position: tuple,
rotor_selection: tuple = (rotor1, rotor2, rotor3), plugb: str = '') -> str:
def enigma(
text: str,
rotor_position: tuple,
rotor_selection: tuple = (rotor1, rotor2, rotor3),
plugb: str = "",
) -> str:
"""
The only difference with real-world enigma is that I allowed string input.
All characters are converted to uppercase. (non-letter symbol are ignored)
@ -179,7 +210,8 @@ def enigma(text: str, rotor_position: tuple,
text = text.upper()
rotor_position, rotor_selection, plugboard = _validator(
rotor_position, rotor_selection, plugb.upper())
rotor_position, rotor_selection, plugb.upper()
)
rotorpos1, rotorpos2, rotorpos3 = rotor_position
rotor1, rotor2, rotor3 = rotor_selection
@ -245,12 +277,12 @@ def enigma(text: str, rotor_position: tuple,
return "".join(result)
if __name__ == '__main__':
message = 'This is my Python script that emulates the Enigma machine from WWII.'
if __name__ == "__main__":
message = "This is my Python script that emulates the Enigma machine from WWII."
rotor_pos = (1, 1, 1)
pb = 'pictures'
pb = "pictures"
rotor_sel = (rotor2, rotor4, rotor8)
en = enigma(message, rotor_pos, rotor_sel, pb)
print('Encrypted message:', en)
print('Decrypted message:', enigma(en, rotor_pos, rotor_sel, pb))
print("Encrypted message:", en)
print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))

View File

@ -118,7 +118,7 @@ def inorder(root: Node):
return
else:
inorder(root.left)
print(root.value, end=" ")
print(root.value, end=",")
inorder(root.right)
@ -130,19 +130,19 @@ def interactTreap(root, args):
>>> root = interactTreap(None, "+1")
>>> inorder(root)
1
1,
>>> root = interactTreap(root, "+3 +5 +17 +19 +2 +16 +4 +0")
>>> 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")
>>> 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")
>>> 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")
>>> inorder(root)
1 2 3 5 16 17 19
1,2,3,5,16,17,19,
>>> root = interactTreap(root, "=0")
Unknown command
"""

View File

@ -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
quadrant.

View File

@ -94,9 +94,7 @@ def not32(i):
def sum32(a, b):
"""
"""
""""""
return (a + b) % 2 ** 32

View File

@ -135,8 +135,7 @@ class Decision_Tree:
class Test_Decision_Tree:
"""Decision Tres test class
"""
"""Decision Tres test class"""
@staticmethod
def helper_mean_squared_error_test(labels, prediction):

View File

@ -19,9 +19,9 @@ def prime_sieve_eratosthenes(num):
print the prime numbers up to n
>>> prime_sieve_eratosthenes(10)
2 3 5 7
2,3,5,7,
>>> 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)]
@ -35,10 +35,13 @@ def prime_sieve_eratosthenes(num):
for prime in range(2, num + 1):
if primes[prime]:
print(prime, end=" ")
print(prime, end=",")
if __name__ == "__main__":
import doctest
doctest.testmod()
num = int(input())
prime_sieve_eratosthenes(num)

View File

@ -63,8 +63,7 @@ def zeller(date_input: str) -> str:
>>> zeller('01-31-19082939')
Traceback (most recent call last):
...
ValueError: Must be 10 characters long
"""
ValueError: Must be 10 characters long"""
# Days of the week for response
days = {

View File

@ -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_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
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"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")
print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n")

View File

@ -16,14 +16,14 @@ def printMaxActivities(start, finish):
>>> finish = [2, 4, 6, 7, 9, 9]
>>> printMaxActivities(start, finish)
The following activities are selected:
0 1 3 4
0,1,3,4,
"""
n = len(finish)
print("The following activities are selected:")
# The first activity is always selected
i = 0
print(i, end=" ")
print(i, end=",")
# Consider rest of the activities
for j in range(n):
@ -32,16 +32,15 @@ def printMaxActivities(start, finish):
# or equal to the finish time of previously
# selected activity, then select it
if start[j] >= finish[i]:
print(j, end=" ")
print(j, end=",")
i = j
# Driver program to test above function
if __name__ == "__main__":
import doctest
doctest.testmod()
start = [1, 3, 0, 5, 8, 5]
finish = [2, 4, 6, 7, 9, 9]
printMaxActivities(start, finish)
"""
The following activities are selected:
0 1 3 4
"""

View File

@ -23,8 +23,7 @@ def solution(n):
product = -1
d = 0
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)
c = n - a - b
if c * c == (a * a + b * b):

View File

@ -29,11 +29,13 @@ def merge_sort(collection: list) -> list:
:param right: right collection
:return: merge result
"""
def _merge():
while left and right:
yield (left if left[0] <= right[0] else right).pop(0)
yield from left
yield from right
return list(_merge())
if len(collection) <= 1:
@ -44,6 +46,7 @@ def merge_sort(collection: list) -> list:
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]

View File

@ -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.
: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
>>> bubble_sort([0, 5, 2, 3, 2])
>>> bubble_sort([0, 5, 2, 3, 2], 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]
>>> bubble_sort([-23, 0, 6, -4, 34])
>>> bubble_sort([-23, 0, 6, -4, 34], 5)
[-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
>>> bubble_sort(['z','a','y','b','x','c'])
>>> bubble_sort(['z','a','y','b','x','c'], 6)
['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):
try:
if list1[i + 1] < num:
list1[i] = list1[i + 1]
list1[i + 1] = num
bubble_sort(list1)
except IndexError:
pass
return list1
return list_data if not swapped else bubble_sort(list_data, length - 1)
if __name__ == "__main__":
list1 = [33, 99, 22, 11, 66]
bubble_sort(list1)
print(list1)
import doctest
doctest.testmod()

View File

@ -16,7 +16,7 @@ def capitalize(sentence: str) -> str:
''
"""
if not sentence:
return ''
return ""
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:]

View File

@ -53,11 +53,11 @@ def pre_order(node: TreeNode) -> None:
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> 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:
return
print(node.data, end=" ")
print(node.data, end=",")
pre_order(node.left)
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_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> 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:
return
in_order(node.left)
print(node.data, end=" ")
print(node.data, end=",")
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_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> 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:
return
post_order(node.left)
post_order(node.right)
print(node.data, end=" ")
print(node.data, end=",")
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_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> 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:
return
@ -127,7 +127,7 @@ def level_order(node: TreeNode) -> None:
q.put(node)
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=" ")
print(node_dequeued.data, end=",")
if node_dequeued.left:
q.put(node_dequeued.left)
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_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> level_order_actual(root)
1
2 3
4 5 6 7
1,
2,3,
4,5,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
@ -159,7 +159,7 @@ def level_order_actual(node: TreeNode) -> None:
list = []
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=" ")
print(node_dequeued.data, end=",")
if node_dequeued.left:
list.append(node_dequeued.left)
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_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> 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:
return
@ -191,7 +191,7 @@ def pre_order_iter(node: TreeNode) -> None:
n = node
while n or stack:
while n: # start from root node, find its left child
print(n.data, end=" ")
print(n.data, end=",")
stack.append(n)
n = n.left
# 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_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> 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:
return
@ -224,7 +224,7 @@ def in_order_iter(node: TreeNode) -> None:
stack.append(n)
n = n.left
n = stack.pop()
print(n.data, end=" ")
print(n.data, end=",")
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_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> 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:
return
@ -256,7 +256,7 @@ def post_order_iter(node: TreeNode) -> None:
stack1.append(n.right)
stack2.append(n)
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: