mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-17 06:48:09 +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)
|
||||
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
|
||||
|
|
|
@ -9,7 +9,7 @@ from sympy import diff
|
|||
|
||||
|
||||
def newton_raphson(func: str, a: int, precision: int = 10 ** -10) -> float:
|
||||
""" Finds root from the point 'a' onwards by Newton-Raphson method
|
||||
"""Finds root from the point 'a' onwards by Newton-Raphson method
|
||||
>>> newton_raphson("sin(x)", 2)
|
||||
3.1415926536808043
|
||||
>>> newton_raphson("x**2 - 5*x +2", 0.4)
|
||||
|
|
|
@ -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))
|
||||
|
|
|
@ -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
|
||||
"""
|
||||
|
|
|
@ -61,7 +61,7 @@ class _DoublyLinkedBase:
|
|||
|
||||
class LinkedDeque(_DoublyLinkedBase):
|
||||
def first(self):
|
||||
""" return first element
|
||||
"""return first element
|
||||
>>> d = LinkedDeque()
|
||||
>>> d.add_first('A').first()
|
||||
'A'
|
||||
|
@ -73,7 +73,7 @@ class LinkedDeque(_DoublyLinkedBase):
|
|||
return self._header._next._data
|
||||
|
||||
def last(self):
|
||||
""" return last element
|
||||
"""return last element
|
||||
>>> d = LinkedDeque()
|
||||
>>> d.add_last('A').last()
|
||||
'A'
|
||||
|
@ -87,14 +87,14 @@ class LinkedDeque(_DoublyLinkedBase):
|
|||
# DEque Insert Operations (At the front, At the end)
|
||||
|
||||
def add_first(self, element):
|
||||
""" insertion in the front
|
||||
"""insertion in the front
|
||||
>>> LinkedDeque().add_first('AV').first()
|
||||
'AV'
|
||||
"""
|
||||
return self._insert(self._header, element, self._header._next)
|
||||
|
||||
def add_last(self, element):
|
||||
""" insertion in the end
|
||||
"""insertion in the end
|
||||
>>> LinkedDeque().add_last('B').last()
|
||||
'B'
|
||||
"""
|
||||
|
@ -103,7 +103,7 @@ class LinkedDeque(_DoublyLinkedBase):
|
|||
# DEqueu Remove Operations (At the front, At the end)
|
||||
|
||||
def remove_first(self):
|
||||
""" removal from the front
|
||||
"""removal from the front
|
||||
>>> d = LinkedDeque()
|
||||
>>> d.is_empty()
|
||||
True
|
||||
|
@ -123,7 +123,7 @@ class LinkedDeque(_DoublyLinkedBase):
|
|||
return self._delete(self._header._next)
|
||||
|
||||
def remove_last(self):
|
||||
""" removal in the end
|
||||
"""removal in the end
|
||||
>>> d = LinkedDeque()
|
||||
>>> d.is_empty()
|
||||
True
|
||||
|
|
|
@ -10,7 +10,7 @@ def is_operand(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.
|
||||
|
||||
https://en.wikipedia.org/wiki/Order_of_operations
|
||||
|
@ -20,7 +20,7 @@ def precedence(char):
|
|||
|
||||
|
||||
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.
|
||||
|
||||
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
|
||||
|
|
|
@ -2,7 +2,7 @@ __author__ = "Omkar Pathak"
|
|||
|
||||
|
||||
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
|
||||
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
|
||||
|
|
|
@ -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):
|
||||
""" divide and conquer approach
|
||||
"""divide and conquer approach
|
||||
|
||||
Parameters :
|
||||
points, points_count (list(tuple(int, int)), int)
|
||||
|
|
|
@ -11,7 +11,7 @@ Ref : INTRODUCTION TO ALGORITHMS THIRD EDITION
|
|||
|
||||
|
||||
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 :
|
||||
array (list[int]) : given array
|
||||
|
@ -30,7 +30,7 @@ def max_sum_from_start(array):
|
|||
|
||||
|
||||
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 :
|
||||
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):
|
||||
""" Maximum contiguous sub-array sum, using divide and conquer method
|
||||
"""Maximum contiguous sub-array sum, using divide and conquer method
|
||||
|
||||
Parameters :
|
||||
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
|
||||
quadrant.
|
||||
|
|
|
@ -94,9 +94,7 @@ def not32(i):
|
|||
|
||||
|
||||
def sum32(a, b):
|
||||
"""
|
||||
|
||||
"""
|
||||
""""""
|
||||
return (a + b) % 2 ** 32
|
||||
|
||||
|
||||
|
|
|
@ -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):
|
||||
|
|
|
@ -153,7 +153,7 @@ def calculate_variance(items: list, means: list, total_count: int) -> float:
|
|||
def predict_y_values(
|
||||
x_items: list, means: list, variance: float, probabilities: 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 means: a list containing real mean values of each class
|
||||
:param variance: calculated value of variance by calculate_variance function
|
||||
|
|
|
@ -12,7 +12,7 @@ import requests
|
|||
|
||||
|
||||
def collect_dataset():
|
||||
""" Collect dataset of CSGO
|
||||
"""Collect dataset of CSGO
|
||||
The dataset contains ADR vs Rating of a Player
|
||||
: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):
|
||||
""" 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_y : contains the output associated with each data-entry
|
||||
: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):
|
||||
""" Return sum of square error for error calculation
|
||||
"""Return sum of square error for error calculation
|
||||
:param data_x : contains our dataset
|
||||
:param data_y : contains the output (result vector)
|
||||
: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):
|
||||
""" Implement Linear regression over the dataset
|
||||
"""Implement Linear regression over the dataset
|
||||
:param data_x : contains our dataset
|
||||
:param data_y : contains the output (result vector)
|
||||
:return : feature for line of best fit (Feature vector)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
def sum_of_geometric_progression(
|
||||
first_term: int, common_ratio: int, num_of_terms: int
|
||||
) -> float:
|
||||
""""
|
||||
""" "
|
||||
Return the sum of n terms in a geometric progression.
|
||||
>>> sum_of_geometric_progression(1, 2, 10)
|
||||
1023.0
|
||||
|
|
|
@ -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 = {
|
||||
|
|
|
@ -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")
|
||||
|
|
|
@ -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
|
||||
start = [1, 3, 0, 5, 8, 5]
|
||||
finish = [2, 4, 6, 7, 9, 9]
|
||||
printMaxActivities(start, finish)
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
"""
|
||||
The following activities are selected:
|
||||
0 1 3 4
|
||||
"""
|
||||
doctest.testmod()
|
||||
|
||||
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):
|
||||
""" 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)
|
||||
@Args:
|
||||
--
|
||||
|
|
|
@ -12,7 +12,7 @@ class LRUCache:
|
|||
|
||||
@abstractmethod
|
||||
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.
|
||||
"""
|
||||
self.dq_store = deque()
|
||||
|
|
|
@ -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):
|
||||
|
|
|
@ -12,7 +12,7 @@ smaller than n when n is smaller than 10 million. Only for positive numbers.
|
|||
|
||||
|
||||
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)
|
||||
142913828922
|
||||
|
|
|
@ -12,16 +12,16 @@ def lattice_paths(n):
|
|||
corner going to bottom right corner and being able to move right and down
|
||||
only.
|
||||
|
||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 50
|
||||
1.008913445455642e+29
|
||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 25
|
||||
126410606437752.0
|
||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 23
|
||||
8233430727600.0
|
||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 15
|
||||
155117520.0
|
||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 1
|
||||
2.0
|
||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 50
|
||||
1.008913445455642e+29
|
||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 25
|
||||
126410606437752.0
|
||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 23
|
||||
8233430727600.0
|
||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 15
|
||||
155117520.0
|
||||
bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 1
|
||||
2.0
|
||||
|
||||
>>> lattice_paths(25)
|
||||
126410606437752
|
||||
|
|
|
@ -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(",")]
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -25,7 +25,7 @@ class BoyerMooreSearch:
|
|||
self.textLen, self.patLen = len(text), len(pattern)
|
||||
|
||||
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 :
|
||||
char (chr): character to be searched
|
||||
|
|
|
@ -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:]
|
||||
|
||||
|
|
|
@ -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:
|
||||
|
|
Loading…
Reference in New Issue
Block a user