mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Pyupgrade to Python 3.9 (#4718)
* Pyupgrade to Python 3.9 * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
parent
5d5831bdd0
commit
cecf43d648
|
@ -545,7 +545,7 @@
|
||||||
## Other
|
## Other
|
||||||
* [Activity Selection](https://github.com/TheAlgorithms/Python/blob/master/other/activity_selection.py)
|
* [Activity Selection](https://github.com/TheAlgorithms/Python/blob/master/other/activity_selection.py)
|
||||||
* [Date To Weekday](https://github.com/TheAlgorithms/Python/blob/master/other/date_to_weekday.py)
|
* [Date To Weekday](https://github.com/TheAlgorithms/Python/blob/master/other/date_to_weekday.py)
|
||||||
* [Davis–Putnam–Logemann–Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davis–putnam–logemann–loveland.py)
|
* [Davisb Putnamb Logemannb Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davisb_putnamb_logemannb_loveland.py)
|
||||||
* [Dijkstra Bankers Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/dijkstra_bankers_algorithm.py)
|
* [Dijkstra Bankers Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/dijkstra_bankers_algorithm.py)
|
||||||
* [Doomsday](https://github.com/TheAlgorithms/Python/blob/master/other/doomsday.py)
|
* [Doomsday](https://github.com/TheAlgorithms/Python/blob/master/other/doomsday.py)
|
||||||
* [Fischer Yates Shuffle](https://github.com/TheAlgorithms/Python/blob/master/other/fischer_yates_shuffle.py)
|
* [Fischer Yates Shuffle](https://github.com/TheAlgorithms/Python/blob/master/other/fischer_yates_shuffle.py)
|
||||||
|
@ -860,6 +860,7 @@
|
||||||
* [Counting Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/counting_sort.py)
|
* [Counting Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/counting_sort.py)
|
||||||
* [Cycle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cycle_sort.py)
|
* [Cycle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cycle_sort.py)
|
||||||
* [Double Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/double_sort.py)
|
* [Double Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/double_sort.py)
|
||||||
|
* [Dutch National Flag Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/dutch_national_flag_sort.py)
|
||||||
* [Exchange Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/exchange_sort.py)
|
* [Exchange Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/exchange_sort.py)
|
||||||
* [External Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/external_sort.py)
|
* [External Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/external_sort.py)
|
||||||
* [Gnome Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/gnome_sort.py)
|
* [Gnome Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/gnome_sort.py)
|
||||||
|
|
|
@ -1,14 +1,14 @@
|
||||||
"""
|
"""
|
||||||
Checks if a system of forces is in static equilibrium.
|
Checks if a system of forces is in static equilibrium.
|
||||||
"""
|
"""
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
from numpy import array, cos, cross, ndarray, radians, sin
|
from numpy import array, cos, cross, ndarray, radians, sin
|
||||||
|
|
||||||
|
|
||||||
def polar_force(
|
def polar_force(
|
||||||
magnitude: float, angle: float, radian_mode: bool = False
|
magnitude: float, angle: float, radian_mode: bool = False
|
||||||
) -> List[float]:
|
) -> list[float]:
|
||||||
"""
|
"""
|
||||||
Resolves force along rectangular components.
|
Resolves force along rectangular components.
|
||||||
(force, angle) => (force_x, force_y)
|
(force, angle) => (force_x, force_y)
|
||||||
|
|
|
@ -3,12 +3,12 @@
|
||||||
Reference:
|
Reference:
|
||||||
- https://en.wikipedia.org/wiki/LU_decomposition
|
- https://en.wikipedia.org/wiki/LU_decomposition
|
||||||
"""
|
"""
|
||||||
from typing import Tuple
|
from __future__ import annotations
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
def lower_upper_decomposition(table: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
|
def lower_upper_decomposition(table: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
||||||
"""Lower-Upper (LU) Decomposition
|
"""Lower-Upper (LU) Decomposition
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/
|
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import math
|
import math
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
# for calculating u value
|
# for calculating u value
|
||||||
|
@ -22,7 +22,7 @@ def ucal(u: float, p: int) -> float:
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
n = int(input("enter the numbers of values: "))
|
n = int(input("enter the numbers of values: "))
|
||||||
y: List[List[float]] = []
|
y: list[list[float]] = []
|
||||||
for i in range(n):
|
for i in range(n):
|
||||||
y.append([])
|
y.append([])
|
||||||
for i in range(n):
|
for i in range(n):
|
||||||
|
|
|
@ -2,15 +2,16 @@
|
||||||
# Author: Syed Haseeb Shah (github.com/QuantumNovice)
|
# Author: Syed Haseeb Shah (github.com/QuantumNovice)
|
||||||
# The Newton-Raphson method (also known as Newton's method) is a way to
|
# The Newton-Raphson method (also known as Newton's method) is a way to
|
||||||
# quickly find a good approximation for the root of a real-valued function
|
# quickly find a good approximation for the root of a real-valued function
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from math import * # noqa: F401, F403
|
from math import * # noqa: F401, F403
|
||||||
from typing import Union
|
|
||||||
|
|
||||||
from sympy import diff
|
from sympy import diff
|
||||||
|
|
||||||
|
|
||||||
def newton_raphson(
|
def newton_raphson(
|
||||||
func: str, a: Union[float, Decimal], precision: float = 10 ** -10
|
func: str, a: float | Decimal, precision: float = 10 ** -10
|
||||||
) -> float:
|
) -> 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,16 +3,16 @@
|
||||||
numbers out of 1 ... n. We use backtracking to solve this problem.
|
numbers out of 1 ... n. We use backtracking to solve this problem.
|
||||||
Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
|
Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
|
||||||
"""
|
"""
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def generate_all_combinations(n: int, k: int) -> List[List[int]]:
|
def generate_all_combinations(n: int, k: int) -> list[list[int]]:
|
||||||
"""
|
"""
|
||||||
>>> generate_all_combinations(n=4, k=2)
|
>>> generate_all_combinations(n=4, k=2)
|
||||||
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
|
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
|
||||||
"""
|
"""
|
||||||
|
|
||||||
result: List[List[int]] = []
|
result: list[list[int]] = []
|
||||||
create_all_state(1, n, k, [], result)
|
create_all_state(1, n, k, [], result)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
@ -21,8 +21,8 @@ def create_all_state(
|
||||||
increment: int,
|
increment: int,
|
||||||
total_number: int,
|
total_number: int,
|
||||||
level: int,
|
level: int,
|
||||||
current_list: List[int],
|
current_list: list[int],
|
||||||
total_list: List[List[int]],
|
total_list: list[list[int]],
|
||||||
) -> None:
|
) -> None:
|
||||||
if level == 0:
|
if level == 0:
|
||||||
total_list.append(current_list[:])
|
total_list.append(current_list[:])
|
||||||
|
@ -34,7 +34,7 @@ def create_all_state(
|
||||||
current_list.pop()
|
current_list.pop()
|
||||||
|
|
||||||
|
|
||||||
def print_all_state(total_list: List[List[int]]) -> None:
|
def print_all_state(total_list: list[list[int]]) -> None:
|
||||||
for i in total_list:
|
for i in total_list:
|
||||||
print(*i)
|
print(*i)
|
||||||
|
|
||||||
|
|
|
@ -5,18 +5,18 @@
|
||||||
Time complexity: O(n! * n),
|
Time complexity: O(n! * n),
|
||||||
where n denotes the length of the given sequence.
|
where n denotes the length of the given sequence.
|
||||||
"""
|
"""
|
||||||
from typing import List, Union
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def generate_all_permutations(sequence: List[Union[int, str]]) -> None:
|
def generate_all_permutations(sequence: list[int | str]) -> None:
|
||||||
create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
|
create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
|
||||||
|
|
||||||
|
|
||||||
def create_state_space_tree(
|
def create_state_space_tree(
|
||||||
sequence: List[Union[int, str]],
|
sequence: list[int | str],
|
||||||
current_sequence: List[Union[int, str]],
|
current_sequence: list[int | str],
|
||||||
index: int,
|
index: int,
|
||||||
index_used: List[int],
|
index_used: list[int],
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Creates a state space tree to iterate through each branch using DFS.
|
Creates a state space tree to iterate through each branch using DFS.
|
||||||
|
@ -44,8 +44,8 @@ print("Enter the elements")
|
||||||
sequence = list(map(int, input().split()))
|
sequence = list(map(int, input().split()))
|
||||||
"""
|
"""
|
||||||
|
|
||||||
sequence: List[Union[int, str]] = [3, 1, 2, 4]
|
sequence: list[int | str] = [3, 1, 2, 4]
|
||||||
generate_all_permutations(sequence)
|
generate_all_permutations(sequence)
|
||||||
|
|
||||||
sequence_2: List[Union[int, str]] = ["A", "B", "C"]
|
sequence_2: list[int | str] = ["A", "B", "C"]
|
||||||
generate_all_permutations(sequence_2)
|
generate_all_permutations(sequence_2)
|
||||||
|
|
|
@ -5,15 +5,17 @@ of the given sequence. We use backtracking to solve this problem.
|
||||||
Time complexity: O(2^n),
|
Time complexity: O(2^n),
|
||||||
where n denotes the length of the given sequence.
|
where n denotes the length of the given sequence.
|
||||||
"""
|
"""
|
||||||
from typing import Any, List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
def generate_all_subsequences(sequence: List[Any]) -> None:
|
def generate_all_subsequences(sequence: list[Any]) -> None:
|
||||||
create_state_space_tree(sequence, [], 0)
|
create_state_space_tree(sequence, [], 0)
|
||||||
|
|
||||||
|
|
||||||
def create_state_space_tree(
|
def create_state_space_tree(
|
||||||
sequence: List[Any], current_subsequence: List[Any], index: int
|
sequence: list[Any], current_subsequence: list[Any], index: int
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Creates a state space tree to iterate through each branch using DFS.
|
Creates a state space tree to iterate through each branch using DFS.
|
||||||
|
@ -32,7 +34,7 @@ def create_state_space_tree(
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
seq: List[Any] = [3, 1, 2, 4]
|
seq: list[Any] = [3, 1, 2, 4]
|
||||||
generate_all_subsequences(seq)
|
generate_all_subsequences(seq)
|
||||||
|
|
||||||
seq.clear()
|
seq.clear()
|
||||||
|
|
|
@ -5,11 +5,10 @@
|
||||||
|
|
||||||
Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring
|
Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring
|
||||||
"""
|
"""
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
def valid_coloring(
|
def valid_coloring(
|
||||||
neighbours: List[int], colored_vertices: List[int], color: int
|
neighbours: list[int], colored_vertices: list[int], color: int
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
For each neighbour check if coloring constraint is satisfied
|
For each neighbour check if coloring constraint is satisfied
|
||||||
|
@ -35,7 +34,7 @@ def valid_coloring(
|
||||||
|
|
||||||
|
|
||||||
def util_color(
|
def util_color(
|
||||||
graph: List[List[int]], max_colors: int, colored_vertices: List[int], index: int
|
graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
Pseudo-Code
|
Pseudo-Code
|
||||||
|
@ -86,7 +85,7 @@ def util_color(
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def color(graph: List[List[int]], max_colors: int) -> List[int]:
|
def color(graph: list[list[int]], max_colors: int) -> list[int]:
|
||||||
"""
|
"""
|
||||||
Wrapper function to call subroutine called util_color
|
Wrapper function to call subroutine called util_color
|
||||||
which will either return True or False.
|
which will either return True or False.
|
||||||
|
|
|
@ -6,11 +6,10 @@
|
||||||
|
|
||||||
Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path
|
Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path
|
||||||
"""
|
"""
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
def valid_connection(
|
def valid_connection(
|
||||||
graph: List[List[int]], next_ver: int, curr_ind: int, path: List[int]
|
graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int]
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
Checks whether it is possible to add next into path by validating 2 statements
|
Checks whether it is possible to add next into path by validating 2 statements
|
||||||
|
@ -47,7 +46,7 @@ def valid_connection(
|
||||||
return not any(vertex == next_ver for vertex in path)
|
return not any(vertex == next_ver for vertex in path)
|
||||||
|
|
||||||
|
|
||||||
def util_hamilton_cycle(graph: List[List[int]], path: List[int], curr_ind: int) -> bool:
|
def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool:
|
||||||
"""
|
"""
|
||||||
Pseudo-Code
|
Pseudo-Code
|
||||||
Base Case:
|
Base Case:
|
||||||
|
@ -108,7 +107,7 @@ def util_hamilton_cycle(graph: List[List[int]], path: List[int], curr_ind: int)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def hamilton_cycle(graph: List[List[int]], start_index: int = 0) -> List[int]:
|
def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]:
|
||||||
r"""
|
r"""
|
||||||
Wrapper function to call subroutine called util_hamilton_cycle,
|
Wrapper function to call subroutine called util_hamilton_cycle,
|
||||||
which will either return array of vertices indicating hamiltonian cycle
|
which will either return array of vertices indicating hamiltonian cycle
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
# Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM
|
# Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM
|
||||||
|
|
||||||
from typing import List, Tuple
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def get_valid_pos(position: Tuple[int, int], n: int) -> List[Tuple[int, int]]:
|
def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]:
|
||||||
"""
|
"""
|
||||||
Find all the valid positions a knight can move to from the current position.
|
Find all the valid positions a knight can move to from the current position.
|
||||||
|
|
||||||
|
@ -32,7 +32,7 @@ def get_valid_pos(position: Tuple[int, int], n: int) -> List[Tuple[int, int]]:
|
||||||
return permissible_positions
|
return permissible_positions
|
||||||
|
|
||||||
|
|
||||||
def is_complete(board: List[List[int]]) -> bool:
|
def is_complete(board: list[list[int]]) -> bool:
|
||||||
"""
|
"""
|
||||||
Check if the board (matrix) has been completely filled with non-zero values.
|
Check if the board (matrix) has been completely filled with non-zero values.
|
||||||
|
|
||||||
|
@ -47,7 +47,7 @@ def is_complete(board: List[List[int]]) -> bool:
|
||||||
|
|
||||||
|
|
||||||
def open_knight_tour_helper(
|
def open_knight_tour_helper(
|
||||||
board: List[List[int]], pos: Tuple[int, int], curr: int
|
board: list[list[int]], pos: tuple[int, int], curr: int
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
Helper function to solve knight tour problem.
|
Helper function to solve knight tour problem.
|
||||||
|
@ -68,7 +68,7 @@ def open_knight_tour_helper(
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def open_knight_tour(n: int) -> List[List[int]]:
|
def open_knight_tour(n: int) -> list[list[int]]:
|
||||||
"""
|
"""
|
||||||
Find the solution for the knight tour problem for a board of size n. Raises
|
Find the solution for the knight tour problem for a board of size n. Raises
|
||||||
ValueError if the tour cannot be performed for the given size.
|
ValueError if the tour cannot be performed for the given size.
|
||||||
|
|
|
@ -7,12 +7,13 @@ if move is of maximizer return true else false
|
||||||
leaves of game tree is stored in scores[]
|
leaves of game tree is stored in scores[]
|
||||||
height is maximum height of Game tree
|
height is maximum height of Game tree
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import math
|
import math
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
def minimax(
|
def minimax(
|
||||||
depth: int, node_index: int, is_max: bool, scores: List[int], height: float
|
depth: int, node_index: int, is_max: bool, scores: list[int], height: float
|
||||||
) -> int:
|
) -> int:
|
||||||
"""
|
"""
|
||||||
>>> import math
|
>>> import math
|
||||||
|
|
|
@ -7,12 +7,12 @@
|
||||||
diagonal lines.
|
diagonal lines.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
solution = []
|
solution = []
|
||||||
|
|
||||||
|
|
||||||
def isSafe(board: List[List[int]], row: int, column: int) -> bool:
|
def isSafe(board: list[list[int]], row: int, column: int) -> bool:
|
||||||
"""
|
"""
|
||||||
This function returns a boolean value True if it is safe to place a queen there
|
This function returns a boolean value True if it is safe to place a queen there
|
||||||
considering the current state of the board.
|
considering the current state of the board.
|
||||||
|
@ -40,7 +40,7 @@ def isSafe(board: List[List[int]], row: int, column: int) -> bool:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def solve(board: List[List[int]], row: int) -> bool:
|
def solve(board: list[list[int]], row: int) -> bool:
|
||||||
"""
|
"""
|
||||||
It creates a state space tree and calls the safe function until it receives a
|
It creates a state space tree and calls the safe function until it receives a
|
||||||
False Boolean and terminates that branch and backtracks to the next
|
False Boolean and terminates that branch and backtracks to the next
|
||||||
|
@ -70,7 +70,7 @@ def solve(board: List[List[int]], row: int) -> bool:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def printboard(board: List[List[int]]) -> None:
|
def printboard(board: list[list[int]]) -> None:
|
||||||
"""
|
"""
|
||||||
Prints the boards that have a successful combination.
|
Prints the boards that have a successful combination.
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -75,14 +75,14 @@ Applying this two formulas we can check if a queen in some position is being att
|
||||||
for another one or vice versa.
|
for another one or vice versa.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def depth_first_search(
|
def depth_first_search(
|
||||||
possible_board: List[int],
|
possible_board: list[int],
|
||||||
diagonal_right_collisions: List[int],
|
diagonal_right_collisions: list[int],
|
||||||
diagonal_left_collisions: List[int],
|
diagonal_left_collisions: list[int],
|
||||||
boards: List[List[str]],
|
boards: list[list[str]],
|
||||||
n: int,
|
n: int,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
|
@ -139,7 +139,7 @@ def depth_first_search(
|
||||||
|
|
||||||
|
|
||||||
def n_queens_solution(n: int) -> None:
|
def n_queens_solution(n: int) -> None:
|
||||||
boards: List[List[str]] = []
|
boards: list[list[str]] = []
|
||||||
depth_first_search([], [], [], boards, n)
|
depth_first_search([], [], [], boards, n)
|
||||||
|
|
||||||
# Print all the boards
|
# Print all the boards
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def solve_maze(maze: List[List[int]]) -> bool:
|
def solve_maze(maze: list[list[int]]) -> bool:
|
||||||
"""
|
"""
|
||||||
This method solves the "rat in maze" problem.
|
This method solves the "rat in maze" problem.
|
||||||
In this problem we have some n by n matrix, a start point and an end point.
|
In this problem we have some n by n matrix, a start point and an end point.
|
||||||
|
@ -70,7 +70,7 @@ def solve_maze(maze: List[List[int]]) -> bool:
|
||||||
return solved
|
return solved
|
||||||
|
|
||||||
|
|
||||||
def run_maze(maze: List[List[int]], i: int, j: int, solutions: List[List[int]]) -> bool:
|
def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]]) -> bool:
|
||||||
"""
|
"""
|
||||||
This method is recursive starting from (i, j) and going in one of four directions:
|
This method is recursive starting from (i, j) and going in one of four directions:
|
||||||
up, down, left, right.
|
up, down, left, right.
|
||||||
|
|
|
@ -9,9 +9,9 @@ function on the next column to see if it returns True. if yes, we
|
||||||
have solved the puzzle. else, we backtrack and place another number
|
have solved the puzzle. else, we backtrack and place another number
|
||||||
in that cell and repeat this process.
|
in that cell and repeat this process.
|
||||||
"""
|
"""
|
||||||
from typing import List, Optional, Tuple
|
from __future__ import annotations
|
||||||
|
|
||||||
Matrix = List[List[int]]
|
Matrix = list[list[int]]
|
||||||
|
|
||||||
# assigning initial values to the grid
|
# assigning initial values to the grid
|
||||||
initial_grid: Matrix = [
|
initial_grid: Matrix = [
|
||||||
|
@ -59,7 +59,7 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def find_empty_location(grid: Matrix) -> Optional[Tuple[int, int]]:
|
def find_empty_location(grid: Matrix) -> tuple[int, int] | None:
|
||||||
"""
|
"""
|
||||||
This function finds an empty location so that we can assign a number
|
This function finds an empty location so that we can assign a number
|
||||||
for that particular row and column.
|
for that particular row and column.
|
||||||
|
@ -71,7 +71,7 @@ def find_empty_location(grid: Matrix) -> Optional[Tuple[int, int]]:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def sudoku(grid: Matrix) -> Optional[Matrix]:
|
def sudoku(grid: Matrix) -> Matrix | None:
|
||||||
"""
|
"""
|
||||||
Takes a partially filled-in grid and attempts to assign values to
|
Takes a partially filled-in grid and attempts to assign values to
|
||||||
all unassigned locations in such a way to meet the requirements
|
all unassigned locations in such a way to meet the requirements
|
||||||
|
|
|
@ -6,12 +6,12 @@
|
||||||
Summation of the chosen numbers must be equal to given number M and one number
|
Summation of the chosen numbers must be equal to given number M and one number
|
||||||
can be used only once.
|
can be used only once.
|
||||||
"""
|
"""
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def generate_sum_of_subsets_soln(nums: List[int], max_sum: int) -> List[List[int]]:
|
def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]:
|
||||||
result: List[List[int]] = []
|
result: list[list[int]] = []
|
||||||
path: List[int] = []
|
path: list[int] = []
|
||||||
num_index = 0
|
num_index = 0
|
||||||
remaining_nums_sum = sum(nums)
|
remaining_nums_sum = sum(nums)
|
||||||
create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum)
|
create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum)
|
||||||
|
@ -19,11 +19,11 @@ def generate_sum_of_subsets_soln(nums: List[int], max_sum: int) -> List[List[int
|
||||||
|
|
||||||
|
|
||||||
def create_state_space_tree(
|
def create_state_space_tree(
|
||||||
nums: List[int],
|
nums: list[int],
|
||||||
max_sum: int,
|
max_sum: int,
|
||||||
num_index: int,
|
num_index: int,
|
||||||
path: List[int],
|
path: list[int],
|
||||||
result: List[List[int]],
|
result: list[list[int]],
|
||||||
remaining_nums_sum: int,
|
remaining_nums_sum: int,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -11,11 +11,11 @@ Algorithm :
|
||||||
1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1
|
1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1
|
||||||
2. Take n = ra*by + rb*ax
|
2. Take n = ra*by + rb*ax
|
||||||
"""
|
"""
|
||||||
from typing import Tuple
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
# Extended Euclid
|
# Extended Euclid
|
||||||
def extended_euclid(a: int, b: int) -> Tuple[int, int]:
|
def extended_euclid(a: int, b: int) -> tuple[int, int]:
|
||||||
"""
|
"""
|
||||||
>>> extended_euclid(10, 6)
|
>>> extended_euclid(10, 6)
|
||||||
(-1, 2)
|
(-1, 2)
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
from typing import Tuple
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def diophantine(a: int, b: int, c: int) -> Tuple[float, float]:
|
def diophantine(a: int, b: int, c: int) -> tuple[float, float]:
|
||||||
"""
|
"""
|
||||||
Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the
|
Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the
|
||||||
diophantine equation a*x + b*y = c has a solution (where x and y are integers)
|
diophantine equation a*x + b*y = c has a solution (where x and y are integers)
|
||||||
|
@ -95,7 +95,7 @@ def greatest_common_divisor(a: int, b: int) -> int:
|
||||||
return b
|
return b
|
||||||
|
|
||||||
|
|
||||||
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
|
def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
|
||||||
"""
|
"""
|
||||||
Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers
|
Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers
|
||||||
x and y, then d = gcd(a,b)
|
x and y, then d = gcd(a,b)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from typing import Tuple
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def modular_division(a: int, b: int, n: int) -> int:
|
def modular_division(a: int, b: int, n: int) -> int:
|
||||||
|
@ -73,7 +73,7 @@ def modular_division2(a: int, b: int, n: int) -> int:
|
||||||
return x
|
return x
|
||||||
|
|
||||||
|
|
||||||
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
|
def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
|
||||||
"""
|
"""
|
||||||
Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x
|
Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x
|
||||||
and y, then d = gcd(a,b)
|
and y, then d = gcd(a,b)
|
||||||
|
@ -101,7 +101,7 @@ def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
|
||||||
return (d, x, y)
|
return (d, x, y)
|
||||||
|
|
||||||
|
|
||||||
def extended_euclid(a: int, b: int) -> Tuple[int, int]:
|
def extended_euclid(a: int, b: int) -> tuple[int, int]:
|
||||||
"""
|
"""
|
||||||
Extended Euclid
|
Extended Euclid
|
||||||
>>> extended_euclid(10, 6)
|
>>> extended_euclid(10, 6)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def compare_string(string1: str, string2: str) -> str:
|
def compare_string(string1: str, string2: str) -> str:
|
||||||
|
@ -22,7 +22,7 @@ def compare_string(string1: str, string2: str) -> str:
|
||||||
return "".join(l1)
|
return "".join(l1)
|
||||||
|
|
||||||
|
|
||||||
def check(binary: List[str]) -> List[str]:
|
def check(binary: list[str]) -> list[str]:
|
||||||
"""
|
"""
|
||||||
>>> check(['0.00.01.5'])
|
>>> check(['0.00.01.5'])
|
||||||
['0.00.01.5']
|
['0.00.01.5']
|
||||||
|
@ -46,7 +46,7 @@ def check(binary: List[str]) -> List[str]:
|
||||||
binary = list(set(temp))
|
binary = list(set(temp))
|
||||||
|
|
||||||
|
|
||||||
def decimal_to_binary(no_of_variable: int, minterms: List[float]) -> List[str]:
|
def decimal_to_binary(no_of_variable: int, minterms: list[float]) -> list[str]:
|
||||||
"""
|
"""
|
||||||
>>> decimal_to_binary(3,[1.5])
|
>>> decimal_to_binary(3,[1.5])
|
||||||
['0.00.01.5']
|
['0.00.01.5']
|
||||||
|
@ -82,7 +82,7 @@ def is_for_table(string1: str, string2: str, count: int) -> bool:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def selection(chart: List[List[int]], prime_implicants: List[str]) -> List[str]:
|
def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]:
|
||||||
"""
|
"""
|
||||||
>>> selection([[1]],['0.00.01.5'])
|
>>> selection([[1]],['0.00.01.5'])
|
||||||
['0.00.01.5']
|
['0.00.01.5']
|
||||||
|
@ -130,8 +130,8 @@ def selection(chart: List[List[int]], prime_implicants: List[str]) -> List[str]:
|
||||||
|
|
||||||
|
|
||||||
def prime_implicant_chart(
|
def prime_implicant_chart(
|
||||||
prime_implicants: List[str], binary: List[str]
|
prime_implicants: list[str], binary: list[str]
|
||||||
) -> List[List[int]]:
|
) -> list[list[int]]:
|
||||||
"""
|
"""
|
||||||
>>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5'])
|
>>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5'])
|
||||||
[[1]]
|
[[1]]
|
||||||
|
|
|
@ -2,11 +2,8 @@
|
||||||
Conway's Game of Life implemented in Python.
|
Conway's Game of Life implemented in Python.
|
||||||
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
|
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import List
|
|
||||||
|
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
# Define glider example
|
# Define glider example
|
||||||
|
@ -25,7 +22,7 @@ GLIDER = [
|
||||||
BLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
|
BLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
|
||||||
|
|
||||||
|
|
||||||
def new_generation(cells: List[List[int]]) -> List[List[int]]:
|
def new_generation(cells: list[list[int]]) -> list[list[int]]:
|
||||||
"""
|
"""
|
||||||
Generates the next generation for a given state of Conway's Game of Life.
|
Generates the next generation for a given state of Conway's Game of Life.
|
||||||
>>> new_generation(BLINKER)
|
>>> new_generation(BLINKER)
|
||||||
|
|
|
@ -1,8 +1,9 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from string import ascii_letters
|
from string import ascii_letters
|
||||||
from typing import Dict, Optional
|
|
||||||
|
|
||||||
|
|
||||||
def encrypt(input_string: str, key: int, alphabet: Optional[str] = None) -> str:
|
def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str:
|
||||||
"""
|
"""
|
||||||
encrypt
|
encrypt
|
||||||
=======
|
=======
|
||||||
|
@ -80,7 +81,7 @@ def encrypt(input_string: str, key: int, alphabet: Optional[str] = None) -> str:
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def decrypt(input_string: str, key: int, alphabet: Optional[str] = None) -> str:
|
def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str:
|
||||||
"""
|
"""
|
||||||
decrypt
|
decrypt
|
||||||
=======
|
=======
|
||||||
|
@ -145,7 +146,7 @@ def decrypt(input_string: str, key: int, alphabet: Optional[str] = None) -> str:
|
||||||
return encrypt(input_string, key, alphabet)
|
return encrypt(input_string, key, alphabet)
|
||||||
|
|
||||||
|
|
||||||
def brute_force(input_string: str, alphabet: Optional[str] = None) -> Dict[int, str]:
|
def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str]:
|
||||||
"""
|
"""
|
||||||
brute_force
|
brute_force
|
||||||
===========
|
===========
|
||||||
|
|
|
@ -1,12 +1,11 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
from __future__ import annotations
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
def decrypt_caesar_with_chi_squared(
|
def decrypt_caesar_with_chi_squared(
|
||||||
ciphertext: str,
|
ciphertext: str,
|
||||||
cipher_alphabet: Optional[list[str]] = None,
|
cipher_alphabet: list[str] | None = None,
|
||||||
frequencies_dict: Optional[dict[str, float]] = None,
|
frequencies_dict: dict[str, float] | None = None,
|
||||||
case_sensetive: bool = False,
|
case_sensetive: bool = False,
|
||||||
) -> tuple[int, float, str]:
|
) -> tuple[int, float, str]:
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
from typing import Optional
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def find_primitive(n: int) -> Optional[int]:
|
def find_primitive(n: int) -> int | None:
|
||||||
for r in range(1, n):
|
for r in range(1, n):
|
||||||
li = []
|
li = []
|
||||||
for x in range(n - 1):
|
for x in range(n - 1):
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import random
|
import random
|
||||||
import string
|
import string
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
class ShuffledShiftCipher:
|
class ShuffledShiftCipher:
|
||||||
|
@ -27,7 +28,7 @@ class ShuffledShiftCipher:
|
||||||
cip2 = ShuffledShiftCipher()
|
cip2 = ShuffledShiftCipher()
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, passcode: Optional[str] = None) -> None:
|
def __init__(self, passcode: str | None = None) -> None:
|
||||||
"""
|
"""
|
||||||
Initializes a cipher object with a passcode as it's entity
|
Initializes a cipher object with a passcode as it's entity
|
||||||
Note: No new passcode is generated if user provides a passcode
|
Note: No new passcode is generated if user provides a passcode
|
||||||
|
|
|
@ -30,7 +30,7 @@ def parse_file(file_path):
|
||||||
if not c:
|
if not c:
|
||||||
break
|
break
|
||||||
chars[c] = chars[c] + 1 if c in chars.keys() else 1
|
chars[c] = chars[c] + 1 if c in chars.keys() else 1
|
||||||
return sorted([Letter(c, f) for c, f in chars.items()], key=lambda l: l.freq)
|
return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq)
|
||||||
|
|
||||||
|
|
||||||
def build_tree(letters):
|
def build_tree(letters):
|
||||||
|
|
|
@ -20,7 +20,7 @@ def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float:
|
||||||
>>> molarity_to_normality(4, 11.4, 5.7)
|
>>> molarity_to_normality(4, 11.4, 5.7)
|
||||||
8
|
8
|
||||||
"""
|
"""
|
||||||
return round((float(moles / volume) * nfactor))
|
return round(float(moles / volume) * nfactor)
|
||||||
|
|
||||||
|
|
||||||
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float:
|
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float:
|
||||||
|
|
|
@ -1,8 +1,9 @@
|
||||||
"""
|
"""
|
||||||
Convert International System of Units (SI) and Binary prefixes
|
Convert International System of Units (SI) and Binary prefixes
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import Union
|
|
||||||
|
|
||||||
|
|
||||||
class SI_Unit(Enum):
|
class SI_Unit(Enum):
|
||||||
|
@ -41,8 +42,8 @@ class Binary_Unit(Enum):
|
||||||
|
|
||||||
def convert_si_prefix(
|
def convert_si_prefix(
|
||||||
known_amount: float,
|
known_amount: float,
|
||||||
known_prefix: Union[str, SI_Unit],
|
known_prefix: str | SI_Unit,
|
||||||
unknown_prefix: Union[str, SI_Unit],
|
unknown_prefix: str | SI_Unit,
|
||||||
) -> float:
|
) -> float:
|
||||||
"""
|
"""
|
||||||
Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix
|
Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix
|
||||||
|
@ -70,8 +71,8 @@ def convert_si_prefix(
|
||||||
|
|
||||||
def convert_binary_prefix(
|
def convert_binary_prefix(
|
||||||
known_amount: float,
|
known_amount: float,
|
||||||
known_prefix: Union[str, Binary_Unit],
|
known_prefix: str | Binary_Unit,
|
||||||
unknown_prefix: Union[str, Binary_Unit],
|
unknown_prefix: str | Binary_Unit,
|
||||||
) -> float:
|
) -> float:
|
||||||
"""
|
"""
|
||||||
Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix
|
Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix
|
||||||
|
|
|
@ -5,15 +5,16 @@ python3 -m doctest -v avl_tree.py
|
||||||
For testing run:
|
For testing run:
|
||||||
python avl_tree.py
|
python avl_tree.py
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import math
|
import math
|
||||||
import random
|
import random
|
||||||
from typing import Any, List, Optional
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
class my_queue:
|
class my_queue:
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.data: List[Any] = []
|
self.data: list[Any] = []
|
||||||
self.head: int = 0
|
self.head: int = 0
|
||||||
self.tail: int = 0
|
self.tail: int = 0
|
||||||
|
|
||||||
|
@ -41,17 +42,17 @@ class my_queue:
|
||||||
class my_node:
|
class my_node:
|
||||||
def __init__(self, data: Any) -> None:
|
def __init__(self, data: Any) -> None:
|
||||||
self.data = data
|
self.data = data
|
||||||
self.left: Optional[my_node] = None
|
self.left: my_node | None = None
|
||||||
self.right: Optional[my_node] = None
|
self.right: my_node | None = None
|
||||||
self.height: int = 1
|
self.height: int = 1
|
||||||
|
|
||||||
def get_data(self) -> Any:
|
def get_data(self) -> Any:
|
||||||
return self.data
|
return self.data
|
||||||
|
|
||||||
def get_left(self) -> Optional["my_node"]:
|
def get_left(self) -> my_node | None:
|
||||||
return self.left
|
return self.left
|
||||||
|
|
||||||
def get_right(self) -> Optional["my_node"]:
|
def get_right(self) -> my_node | None:
|
||||||
return self.right
|
return self.right
|
||||||
|
|
||||||
def get_height(self) -> int:
|
def get_height(self) -> int:
|
||||||
|
@ -61,11 +62,11 @@ class my_node:
|
||||||
self.data = data
|
self.data = data
|
||||||
return
|
return
|
||||||
|
|
||||||
def set_left(self, node: Optional["my_node"]) -> None:
|
def set_left(self, node: my_node | None) -> None:
|
||||||
self.left = node
|
self.left = node
|
||||||
return
|
return
|
||||||
|
|
||||||
def set_right(self, node: Optional["my_node"]) -> None:
|
def set_right(self, node: my_node | None) -> None:
|
||||||
self.right = node
|
self.right = node
|
||||||
return
|
return
|
||||||
|
|
||||||
|
@ -74,7 +75,7 @@ class my_node:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
def get_height(node: Optional["my_node"]) -> int:
|
def get_height(node: my_node | None) -> int:
|
||||||
if node is None:
|
if node is None:
|
||||||
return 0
|
return 0
|
||||||
return node.get_height()
|
return node.get_height()
|
||||||
|
@ -149,7 +150,7 @@ def rl_rotation(node: my_node) -> my_node:
|
||||||
return left_rotation(node)
|
return left_rotation(node)
|
||||||
|
|
||||||
|
|
||||||
def insert_node(node: Optional["my_node"], data: Any) -> Optional["my_node"]:
|
def insert_node(node: my_node | None, data: Any) -> my_node | None:
|
||||||
if node is None:
|
if node is None:
|
||||||
return my_node(data)
|
return my_node(data)
|
||||||
if data < node.get_data():
|
if data < node.get_data():
|
||||||
|
@ -197,7 +198,7 @@ def get_leftMost(root: my_node) -> Any:
|
||||||
return root.get_data()
|
return root.get_data()
|
||||||
|
|
||||||
|
|
||||||
def del_node(root: my_node, data: Any) -> Optional["my_node"]:
|
def del_node(root: my_node, data: Any) -> my_node | None:
|
||||||
left_child = root.get_left()
|
left_child = root.get_left()
|
||||||
right_child = root.get_right()
|
right_child = root.get_right()
|
||||||
if root.get_data() == data:
|
if root.get_data() == data:
|
||||||
|
@ -275,7 +276,7 @@ class AVLtree:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.root: Optional[my_node] = None
|
self.root: my_node | None = None
|
||||||
|
|
||||||
def get_height(self) -> int:
|
def get_height(self) -> int:
|
||||||
return get_height(self.root)
|
return get_height(self.root)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from typing import Optional
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
class Node:
|
class Node:
|
||||||
|
@ -8,11 +8,11 @@ class Node:
|
||||||
|
|
||||||
def __init__(self, data: int) -> None:
|
def __init__(self, data: int) -> None:
|
||||||
self.data = data
|
self.data = data
|
||||||
self.left: Optional[Node] = None
|
self.left: Node | None = None
|
||||||
self.right: Optional[Node] = None
|
self.right: Node | None = None
|
||||||
|
|
||||||
|
|
||||||
def display(tree: Optional[Node]) -> None: # In Order traversal of the tree
|
def display(tree: Node | None) -> None: # In Order traversal of the tree
|
||||||
"""
|
"""
|
||||||
>>> root = Node(1)
|
>>> root = Node(1)
|
||||||
>>> root.left = Node(0)
|
>>> root.left = Node(0)
|
||||||
|
@ -30,7 +30,7 @@ def display(tree: Optional[Node]) -> None: # In Order traversal of the tree
|
||||||
display(tree.right)
|
display(tree.right)
|
||||||
|
|
||||||
|
|
||||||
def depth_of_tree(tree: Optional[Node]) -> int:
|
def depth_of_tree(tree: Node | None) -> int:
|
||||||
"""
|
"""
|
||||||
Recursive function that returns the depth of a binary tree.
|
Recursive function that returns the depth of a binary tree.
|
||||||
|
|
||||||
|
|
|
@ -7,21 +7,23 @@ python -m unittest binary_search_tree_recursive.py
|
||||||
To run an example:
|
To run an example:
|
||||||
python binary_search_tree_recursive.py
|
python binary_search_tree_recursive.py
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import unittest
|
import unittest
|
||||||
from typing import Iterator, Optional
|
from typing import Iterator
|
||||||
|
|
||||||
|
|
||||||
class Node:
|
class Node:
|
||||||
def __init__(self, label: int, parent: Optional["Node"]) -> None:
|
def __init__(self, label: int, parent: Node | None) -> None:
|
||||||
self.label = label
|
self.label = label
|
||||||
self.parent = parent
|
self.parent = parent
|
||||||
self.left: Optional[Node] = None
|
self.left: Node | None = None
|
||||||
self.right: Optional[Node] = None
|
self.right: Node | None = None
|
||||||
|
|
||||||
|
|
||||||
class BinarySearchTree:
|
class BinarySearchTree:
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.root: Optional[Node] = None
|
self.root: Node | None = None
|
||||||
|
|
||||||
def empty(self) -> None:
|
def empty(self) -> None:
|
||||||
"""
|
"""
|
||||||
|
@ -66,9 +68,7 @@ class BinarySearchTree:
|
||||||
"""
|
"""
|
||||||
self.root = self._put(self.root, label)
|
self.root = self._put(self.root, label)
|
||||||
|
|
||||||
def _put(
|
def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Node:
|
||||||
self, node: Optional[Node], label: int, parent: Optional[Node] = None
|
|
||||||
) -> Node:
|
|
||||||
if node is None:
|
if node is None:
|
||||||
node = Node(label, parent)
|
node = Node(label, parent)
|
||||||
else:
|
else:
|
||||||
|
@ -98,7 +98,7 @@ class BinarySearchTree:
|
||||||
"""
|
"""
|
||||||
return self._search(self.root, label)
|
return self._search(self.root, label)
|
||||||
|
|
||||||
def _search(self, node: Optional[Node], label: int) -> Node:
|
def _search(self, node: Node | None, label: int) -> Node:
|
||||||
if node is None:
|
if node is None:
|
||||||
raise Exception(f"Node with label {label} does not exist")
|
raise Exception(f"Node with label {label} does not exist")
|
||||||
else:
|
else:
|
||||||
|
@ -140,7 +140,7 @@ class BinarySearchTree:
|
||||||
else:
|
else:
|
||||||
self._reassign_nodes(node, None)
|
self._reassign_nodes(node, None)
|
||||||
|
|
||||||
def _reassign_nodes(self, node: Node, new_children: Optional[Node]) -> None:
|
def _reassign_nodes(self, node: Node, new_children: Node | None) -> None:
|
||||||
if new_children:
|
if new_children:
|
||||||
new_children.parent = node.parent
|
new_children.parent = node.parent
|
||||||
|
|
||||||
|
@ -244,7 +244,7 @@ class BinarySearchTree:
|
||||||
"""
|
"""
|
||||||
return self._inorder_traversal(self.root)
|
return self._inorder_traversal(self.root)
|
||||||
|
|
||||||
def _inorder_traversal(self, node: Optional[Node]) -> Iterator[Node]:
|
def _inorder_traversal(self, node: Node | None) -> Iterator[Node]:
|
||||||
if node is not None:
|
if node is not None:
|
||||||
yield from self._inorder_traversal(node.left)
|
yield from self._inorder_traversal(node.left)
|
||||||
yield node
|
yield node
|
||||||
|
@ -266,7 +266,7 @@ class BinarySearchTree:
|
||||||
"""
|
"""
|
||||||
return self._preorder_traversal(self.root)
|
return self._preorder_traversal(self.root)
|
||||||
|
|
||||||
def _preorder_traversal(self, node: Optional[Node]) -> Iterator[Node]:
|
def _preorder_traversal(self, node: Node | None) -> Iterator[Node]:
|
||||||
if node is not None:
|
if node is not None:
|
||||||
yield node
|
yield node
|
||||||
yield from self._preorder_traversal(node.left)
|
yield from self._preorder_traversal(node.left)
|
||||||
|
|
|
@ -1,13 +1,14 @@
|
||||||
# https://en.wikipedia.org/wiki/Tree_traversal
|
# https://en.wikipedia.org/wiki/Tree_traversal
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Node:
|
class Node:
|
||||||
data: int
|
data: int
|
||||||
left: Optional["Node"] = None
|
left: Node | None = None
|
||||||
right: Optional["Node"] = None
|
right: Node | None = None
|
||||||
|
|
||||||
|
|
||||||
def make_tree() -> Node:
|
def make_tree() -> Node:
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import math
|
import math
|
||||||
from typing import List, Union
|
|
||||||
|
|
||||||
|
|
||||||
class SegmentTree:
|
class SegmentTree:
|
||||||
|
@ -38,7 +37,7 @@ class SegmentTree:
|
||||||
return idx * 2 + 1
|
return idx * 2 + 1
|
||||||
|
|
||||||
def build(
|
def build(
|
||||||
self, idx: int, left_element: int, right_element: int, A: List[int]
|
self, idx: int, left_element: int, right_element: int, A: list[int]
|
||||||
) -> None:
|
) -> None:
|
||||||
if left_element == right_element:
|
if left_element == right_element:
|
||||||
self.segment_tree[idx] = A[left_element - 1]
|
self.segment_tree[idx] = A[left_element - 1]
|
||||||
|
@ -89,7 +88,7 @@ class SegmentTree:
|
||||||
# query with O(lg n)
|
# query with O(lg n)
|
||||||
def query(
|
def query(
|
||||||
self, idx: int, left_element: int, right_element: int, a: int, b: int
|
self, idx: int, left_element: int, right_element: int, a: int, b: int
|
||||||
) -> Union[int, float]:
|
) -> int | float:
|
||||||
"""
|
"""
|
||||||
query(1, 1, size, a, b) for query max of [a,b]
|
query(1, 1, size, a, b) for query max of [a,b]
|
||||||
>>> A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
|
>>> A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
|
||||||
|
|
|
@ -5,7 +5,7 @@ The rule for merging is that if two nodes overlap, then put the value sum of
|
||||||
both nodes to the new value of the merged node. Otherwise, the NOT null node
|
both nodes to the new value of the merged node. Otherwise, the NOT null node
|
||||||
will be used as the node of new tree.
|
will be used as the node of new tree.
|
||||||
"""
|
"""
|
||||||
from typing import Optional
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
class Node:
|
class Node:
|
||||||
|
@ -15,11 +15,11 @@ class Node:
|
||||||
|
|
||||||
def __init__(self, value: int = 0) -> None:
|
def __init__(self, value: int = 0) -> None:
|
||||||
self.value = value
|
self.value = value
|
||||||
self.left: Optional[Node] = None
|
self.left: Node | None = None
|
||||||
self.right: Optional[Node] = None
|
self.right: Node | None = None
|
||||||
|
|
||||||
|
|
||||||
def merge_two_binary_trees(tree1: Optional[Node], tree2: Optional[Node]) -> Node:
|
def merge_two_binary_trees(tree1: Node | None, tree2: Node | None) -> Node:
|
||||||
"""
|
"""
|
||||||
Returns root node of the merged tree.
|
Returns root node of the merged tree.
|
||||||
|
|
||||||
|
@ -52,7 +52,7 @@ def merge_two_binary_trees(tree1: Optional[Node], tree2: Optional[Node]) -> Node
|
||||||
return tree1
|
return tree1
|
||||||
|
|
||||||
|
|
||||||
def print_preorder(root: Optional[Node]) -> None:
|
def print_preorder(root: Node | None) -> None:
|
||||||
"""
|
"""
|
||||||
Print pre-order traversal of the tree.
|
Print pre-order traversal of the tree.
|
||||||
|
|
||||||
|
|
|
@ -2,7 +2,9 @@
|
||||||
python/black : true
|
python/black : true
|
||||||
flake8 : passed
|
flake8 : passed
|
||||||
"""
|
"""
|
||||||
from typing import Iterator, Optional
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Iterator
|
||||||
|
|
||||||
|
|
||||||
class RedBlackTree:
|
class RedBlackTree:
|
||||||
|
@ -21,11 +23,11 @@ class RedBlackTree:
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
label: Optional[int] = None,
|
label: int | None = None,
|
||||||
color: int = 0,
|
color: int = 0,
|
||||||
parent: Optional["RedBlackTree"] = None,
|
parent: RedBlackTree | None = None,
|
||||||
left: Optional["RedBlackTree"] = None,
|
left: RedBlackTree | None = None,
|
||||||
right: Optional["RedBlackTree"] = None,
|
right: RedBlackTree | None = 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
|
||||||
|
@ -42,7 +44,7 @@ class RedBlackTree:
|
||||||
|
|
||||||
# Here are functions which are specific to red-black trees
|
# Here are functions which are specific to red-black trees
|
||||||
|
|
||||||
def rotate_left(self) -> "RedBlackTree":
|
def rotate_left(self) -> RedBlackTree:
|
||||||
"""Rotate the subtree rooted at this node to the left and
|
"""Rotate the subtree rooted at this node to the left and
|
||||||
returns the new root to this subtree.
|
returns the new root to this subtree.
|
||||||
Performing one rotation can be done in O(1).
|
Performing one rotation can be done in O(1).
|
||||||
|
@ -62,7 +64,7 @@ class RedBlackTree:
|
||||||
right.parent = parent
|
right.parent = parent
|
||||||
return right
|
return right
|
||||||
|
|
||||||
def rotate_right(self) -> "RedBlackTree":
|
def rotate_right(self) -> RedBlackTree:
|
||||||
"""Rotate the subtree rooted at this node to the right and
|
"""Rotate the subtree rooted at this node to the right and
|
||||||
returns the new root to this subtree.
|
returns the new root to this subtree.
|
||||||
Performing one rotation can be done in O(1).
|
Performing one rotation can be done in O(1).
|
||||||
|
@ -82,7 +84,7 @@ class RedBlackTree:
|
||||||
left.parent = parent
|
left.parent = parent
|
||||||
return left
|
return left
|
||||||
|
|
||||||
def insert(self, label: int) -> "RedBlackTree":
|
def insert(self, label: int) -> RedBlackTree:
|
||||||
"""Inserts label into the subtree rooted at self, performs any
|
"""Inserts label into the subtree rooted at self, performs any
|
||||||
rotations necessary to maintain balance, and then returns the
|
rotations necessary to maintain balance, and then returns the
|
||||||
new root to this subtree (likely self).
|
new root to this subtree (likely self).
|
||||||
|
@ -139,7 +141,7 @@ class RedBlackTree:
|
||||||
self.grandparent.color = 1
|
self.grandparent.color = 1
|
||||||
self.grandparent._insert_repair()
|
self.grandparent._insert_repair()
|
||||||
|
|
||||||
def remove(self, label: int) -> "RedBlackTree":
|
def remove(self, label: int) -> RedBlackTree:
|
||||||
"""Remove label from this tree."""
|
"""Remove label from this tree."""
|
||||||
if self.label == label:
|
if self.label == label:
|
||||||
if self.left and self.right:
|
if self.left and self.right:
|
||||||
|
@ -337,7 +339,7 @@ class RedBlackTree:
|
||||||
"""
|
"""
|
||||||
return self.search(label) is not None
|
return self.search(label) is not None
|
||||||
|
|
||||||
def search(self, label: int) -> "RedBlackTree":
|
def search(self, label: int) -> RedBlackTree:
|
||||||
"""Search through the tree for label, returning its node if
|
"""Search through the tree for label, returning its node if
|
||||||
it's found, and None otherwise.
|
it's found, and None otherwise.
|
||||||
This method is guaranteed to run in O(log(n)) time.
|
This method is guaranteed to run in O(log(n)) time.
|
||||||
|
@ -411,7 +413,7 @@ class RedBlackTree:
|
||||||
return self.label
|
return self.label
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def grandparent(self) -> "RedBlackTree":
|
def grandparent(self) -> RedBlackTree:
|
||||||
"""Get the current node's grandparent, or None if it doesn't exist."""
|
"""Get the current node's grandparent, or None if it doesn't exist."""
|
||||||
if self.parent is None:
|
if self.parent is None:
|
||||||
return None
|
return None
|
||||||
|
@ -419,7 +421,7 @@ class RedBlackTree:
|
||||||
return self.parent.parent
|
return self.parent.parent
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def sibling(self) -> "RedBlackTree":
|
def sibling(self) -> RedBlackTree:
|
||||||
"""Get the current node's sibling, or None if it doesn't exist."""
|
"""Get the current node's sibling, or None if it doesn't exist."""
|
||||||
if self.parent is None:
|
if self.parent is None:
|
||||||
return None
|
return None
|
||||||
|
|
|
@ -1,9 +1,6 @@
|
||||||
# flake8: noqa
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from random import random
|
from random import random
|
||||||
from typing import Optional, Tuple
|
|
||||||
|
|
||||||
|
|
||||||
class Node:
|
class Node:
|
||||||
|
@ -12,11 +9,11 @@ class Node:
|
||||||
Treap is a binary tree by value and heap by priority
|
Treap is a binary tree by value and heap by priority
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, value: Optional[int] = None):
|
def __init__(self, value: int | None = None):
|
||||||
self.value = value
|
self.value = value
|
||||||
self.prior = random()
|
self.prior = random()
|
||||||
self.left: Optional[Node] = None
|
self.left: Node | None = None
|
||||||
self.right: Optional[Node] = None
|
self.right: Node | None = None
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
from pprint import pformat
|
from pprint import pformat
|
||||||
|
@ -35,7 +32,7 @@ class Node:
|
||||||
return value + left + right
|
return value + left + right
|
||||||
|
|
||||||
|
|
||||||
def split(root: Optional[Node], value: int) -> Tuple[Optional[Node], Optional[Node]]:
|
def split(root: Node | None, value: int) -> tuple[Node | None, Node | None]:
|
||||||
"""
|
"""
|
||||||
We split current tree into 2 trees with value:
|
We split current tree into 2 trees with value:
|
||||||
|
|
||||||
|
@ -64,7 +61,7 @@ def split(root: Optional[Node], value: int) -> Tuple[Optional[Node], Optional[No
|
||||||
return root, right
|
return root, right
|
||||||
|
|
||||||
|
|
||||||
def merge(left: Optional[Node], right: Optional[Node]) -> Optional[Node]:
|
def merge(left: Node | None, right: Node | None) -> Node | None:
|
||||||
"""
|
"""
|
||||||
We merge 2 trees into one.
|
We merge 2 trees into one.
|
||||||
Note: all left tree's values must be less than all right tree's
|
Note: all left tree's values must be less than all right tree's
|
||||||
|
@ -86,7 +83,7 @@ def merge(left: Optional[Node], right: Optional[Node]) -> Optional[Node]:
|
||||||
return right
|
return right
|
||||||
|
|
||||||
|
|
||||||
def insert(root: Optional[Node], value: int) -> Optional[Node]:
|
def insert(root: Node | None, value: int) -> Node | None:
|
||||||
"""
|
"""
|
||||||
Insert element
|
Insert element
|
||||||
|
|
||||||
|
@ -99,7 +96,7 @@ def insert(root: Optional[Node], value: int) -> Optional[Node]:
|
||||||
return merge(merge(left, node), right)
|
return merge(merge(left, node), right)
|
||||||
|
|
||||||
|
|
||||||
def erase(root: Optional[Node], value: int) -> Optional[Node]:
|
def erase(root: Node | None, value: int) -> Node | None:
|
||||||
"""
|
"""
|
||||||
Erase element
|
Erase element
|
||||||
|
|
||||||
|
@ -112,7 +109,7 @@ def erase(root: Optional[Node], value: int) -> Optional[Node]:
|
||||||
return merge(left, right)
|
return merge(left, right)
|
||||||
|
|
||||||
|
|
||||||
def inorder(root: Optional[Node]) -> None:
|
def inorder(root: Node | None) -> None:
|
||||||
"""
|
"""
|
||||||
Just recursive print of a tree
|
Just recursive print of a tree
|
||||||
"""
|
"""
|
||||||
|
@ -124,7 +121,7 @@ def inorder(root: Optional[Node]) -> None:
|
||||||
inorder(root.right)
|
inorder(root.right)
|
||||||
|
|
||||||
|
|
||||||
def interactTreap(root: Optional[Node], args: str) -> Optional[Node]:
|
def interactTreap(root: Node | None, args: str) -> Node | None:
|
||||||
"""
|
"""
|
||||||
Commands:
|
Commands:
|
||||||
+ value to add value into treap
|
+ value to add value into treap
|
||||||
|
|
|
@ -7,8 +7,7 @@ such as the with segment trees or fenwick trees. You can read more about them he
|
||||||
2. https://www.youtube.com/watch?v=4aSv9PcecDw&t=811s
|
2. https://www.youtube.com/watch?v=4aSv9PcecDw&t=811s
|
||||||
3. https://www.youtube.com/watch?v=CybAgVF-MMc&t=1178s
|
3. https://www.youtube.com/watch?v=CybAgVF-MMc&t=1178s
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7]
|
test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7]
|
||||||
|
|
||||||
|
@ -18,8 +17,8 @@ class Node:
|
||||||
self.minn: int = -1
|
self.minn: int = -1
|
||||||
self.maxx: int = -1
|
self.maxx: int = -1
|
||||||
self.map_left: list[int] = [-1] * length
|
self.map_left: list[int] = [-1] * length
|
||||||
self.left: Optional[Node] = None
|
self.left: Node | None = None
|
||||||
self.right: Optional[Node] = None
|
self.right: Node | None = None
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -19,7 +19,7 @@ class HashTable:
|
||||||
return self._keys
|
return self._keys
|
||||||
|
|
||||||
def balanced_factor(self):
|
def balanced_factor(self):
|
||||||
return sum([1 for slot in self.values if slot is not None]) / (
|
return sum(1 for slot in self.values if slot is not None) / (
|
||||||
self.size_table * self.charge_factor
|
self.size_table * self.charge_factor
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
@ -14,7 +14,7 @@ class HashTableWithLinkedList(HashTable):
|
||||||
|
|
||||||
def balanced_factor(self):
|
def balanced_factor(self):
|
||||||
return (
|
return (
|
||||||
sum([self.charge_factor - len(slot) for slot in self.values])
|
sum(self.charge_factor - len(slot) for slot in self.values)
|
||||||
/ self.size_table
|
/ self.size_table
|
||||||
* self.charge_factor
|
* self.charge_factor
|
||||||
)
|
)
|
||||||
|
|
|
@ -1,4 +1,6 @@
|
||||||
from typing import Iterable, List, Optional
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Iterable
|
||||||
|
|
||||||
|
|
||||||
class Heap:
|
class Heap:
|
||||||
|
@ -25,19 +27,19 @@ class Heap:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.h: List[float] = []
|
self.h: list[float] = []
|
||||||
self.heap_size: int = 0
|
self.heap_size: int = 0
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
return str(self.h)
|
return str(self.h)
|
||||||
|
|
||||||
def parent_index(self, child_idx: int) -> Optional[int]:
|
def parent_index(self, child_idx: int) -> int | None:
|
||||||
"""return the parent index of given child"""
|
"""return the parent index of given child"""
|
||||||
if child_idx > 0:
|
if child_idx > 0:
|
||||||
return (child_idx - 1) // 2
|
return (child_idx - 1) // 2
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def left_child_idx(self, parent_idx: int) -> Optional[int]:
|
def left_child_idx(self, parent_idx: int) -> int | None:
|
||||||
"""
|
"""
|
||||||
return the left child index if the left child exists.
|
return the left child index if the left child exists.
|
||||||
if not, return None.
|
if not, return None.
|
||||||
|
@ -47,7 +49,7 @@ class Heap:
|
||||||
return left_child_index
|
return left_child_index
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def right_child_idx(self, parent_idx: int) -> Optional[int]:
|
def right_child_idx(self, parent_idx: int) -> int | None:
|
||||||
"""
|
"""
|
||||||
return the right child index if the right child exists.
|
return the right child index if the right child exists.
|
||||||
if not, return None.
|
if not, return None.
|
||||||
|
|
|
@ -3,7 +3,7 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import random
|
import random
|
||||||
from typing import Generic, Iterable, List, Optional, TypeVar
|
from typing import Generic, Iterable, TypeVar
|
||||||
|
|
||||||
T = TypeVar("T")
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
@ -16,8 +16,8 @@ class RandomizedHeapNode(Generic[T]):
|
||||||
|
|
||||||
def __init__(self, value: T) -> None:
|
def __init__(self, value: T) -> None:
|
||||||
self._value: T = value
|
self._value: T = value
|
||||||
self.left: Optional[RandomizedHeapNode[T]] = None
|
self.left: RandomizedHeapNode[T] | None = None
|
||||||
self.right: Optional[RandomizedHeapNode[T]] = None
|
self.right: RandomizedHeapNode[T] | None = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def value(self) -> T:
|
def value(self) -> T:
|
||||||
|
@ -26,8 +26,8 @@ class RandomizedHeapNode(Generic[T]):
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def merge(
|
def merge(
|
||||||
root1: Optional[RandomizedHeapNode[T]], root2: Optional[RandomizedHeapNode[T]]
|
root1: RandomizedHeapNode[T] | None, root2: RandomizedHeapNode[T] | None
|
||||||
) -> Optional[RandomizedHeapNode[T]]:
|
) -> RandomizedHeapNode[T] | None:
|
||||||
"""Merge 2 nodes together."""
|
"""Merge 2 nodes together."""
|
||||||
if not root1:
|
if not root1:
|
||||||
return root2
|
return root2
|
||||||
|
@ -69,13 +69,13 @@ class RandomizedHeap(Generic[T]):
|
||||||
[-1, 0, 1]
|
[-1, 0, 1]
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, data: Optional[Iterable[T]] = ()) -> None:
|
def __init__(self, data: Iterable[T] | None = ()) -> None:
|
||||||
"""
|
"""
|
||||||
>>> rh = RandomizedHeap([3, 1, 3, 7])
|
>>> rh = RandomizedHeap([3, 1, 3, 7])
|
||||||
>>> rh.to_sorted_list()
|
>>> rh.to_sorted_list()
|
||||||
[1, 3, 3, 7]
|
[1, 3, 3, 7]
|
||||||
"""
|
"""
|
||||||
self._root: Optional[RandomizedHeapNode[T]] = None
|
self._root: RandomizedHeapNode[T] | None = None
|
||||||
for item in data:
|
for item in data:
|
||||||
self.insert(item)
|
self.insert(item)
|
||||||
|
|
||||||
|
@ -151,7 +151,7 @@ class RandomizedHeap(Generic[T]):
|
||||||
"""
|
"""
|
||||||
self._root = None
|
self._root = None
|
||||||
|
|
||||||
def to_sorted_list(self) -> List[T]:
|
def to_sorted_list(self) -> list[T]:
|
||||||
"""
|
"""
|
||||||
Returns sorted list containing all the values in the heap.
|
Returns sorted list containing all the values in the heap.
|
||||||
|
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Generic, Iterable, Iterator, Optional, TypeVar
|
from typing import Generic, Iterable, Iterator, TypeVar
|
||||||
|
|
||||||
T = TypeVar("T")
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
@ -15,8 +15,8 @@ class SkewNode(Generic[T]):
|
||||||
|
|
||||||
def __init__(self, value: T) -> None:
|
def __init__(self, value: T) -> None:
|
||||||
self._value: T = value
|
self._value: T = value
|
||||||
self.left: Optional[SkewNode[T]] = None
|
self.left: SkewNode[T] | None = None
|
||||||
self.right: Optional[SkewNode[T]] = None
|
self.right: SkewNode[T] | None = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def value(self) -> T:
|
def value(self) -> T:
|
||||||
|
@ -25,8 +25,8 @@ class SkewNode(Generic[T]):
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def merge(
|
def merge(
|
||||||
root1: Optional[SkewNode[T]], root2: Optional[SkewNode[T]]
|
root1: SkewNode[T] | None, root2: SkewNode[T] | None
|
||||||
) -> Optional[SkewNode[T]]:
|
) -> SkewNode[T] | None:
|
||||||
"""Merge 2 nodes together."""
|
"""Merge 2 nodes together."""
|
||||||
if not root1:
|
if not root1:
|
||||||
return root2
|
return root2
|
||||||
|
@ -69,13 +69,13 @@ class SkewHeap(Generic[T]):
|
||||||
[-1, 0, 1]
|
[-1, 0, 1]
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, data: Optional[Iterable[T]] = ()) -> None:
|
def __init__(self, data: Iterable[T] | None = ()) -> None:
|
||||||
"""
|
"""
|
||||||
>>> sh = SkewHeap([3, 1, 3, 7])
|
>>> sh = SkewHeap([3, 1, 3, 7])
|
||||||
>>> list(sh)
|
>>> list(sh)
|
||||||
[1, 3, 3, 7]
|
[1, 3, 3, 7]
|
||||||
"""
|
"""
|
||||||
self._root: Optional[SkewNode[T]] = None
|
self._root: SkewNode[T] | None = None
|
||||||
for item in data:
|
for item in data:
|
||||||
self.insert(item)
|
self.insert(item)
|
||||||
|
|
||||||
|
|
|
@ -5,7 +5,6 @@ from __future__ import annotations
|
||||||
|
|
||||||
from collections.abc import Iterable, Iterator
|
from collections.abc import Iterable, Iterator
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1)
|
test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1)
|
||||||
test_data_even = (4, 6, 2, 0, 8, 10, 3, -2)
|
test_data_even = (4, 6, 2, 0, 8, 10, 3, -2)
|
||||||
|
@ -14,12 +13,12 @@ test_data_even = (4, 6, 2, 0, 8, 10, 3, -2)
|
||||||
@dataclass
|
@dataclass
|
||||||
class Node:
|
class Node:
|
||||||
data: int
|
data: int
|
||||||
next: Optional[Node]
|
next: Node | None
|
||||||
|
|
||||||
|
|
||||||
class SortedLinkedList:
|
class SortedLinkedList:
|
||||||
def __init__(self, ints: Iterable[int]) -> None:
|
def __init__(self, ints: Iterable[int]) -> None:
|
||||||
self.head: Optional[Node] = None
|
self.head: Node | None = None
|
||||||
for i in reversed(sorted(ints)):
|
for i in reversed(sorted(ints)):
|
||||||
self.head = Node(i, self.head)
|
self.head = Node(i, self.head)
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
class Node:
|
class Node:
|
||||||
|
@ -16,7 +16,7 @@ class Node:
|
||||||
return "->".join(string_rep)
|
return "->".join(string_rep)
|
||||||
|
|
||||||
|
|
||||||
def make_linked_list(elements_list: List):
|
def make_linked_list(elements_list: list):
|
||||||
"""Creates a Linked List from the elements of the given sequence
|
"""Creates a Linked List from the elements of the given sequence
|
||||||
(list/tuple) and returns the head of the Linked List.
|
(list/tuple) and returns the head of the Linked List.
|
||||||
>>> make_linked_list([])
|
>>> make_linked_list([])
|
||||||
|
|
|
@ -2,11 +2,10 @@
|
||||||
Based on "Skip Lists: A Probabilistic Alternative to Balanced Trees" by William Pugh
|
Based on "Skip Lists: A Probabilistic Alternative to Balanced Trees" by William Pugh
|
||||||
https://epaperpress.com/sortsearch/download/skiplist.pdf
|
https://epaperpress.com/sortsearch/download/skiplist.pdf
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from random import random
|
from random import random
|
||||||
from typing import Generic, Optional, TypeVar
|
from typing import Generic, TypeVar
|
||||||
|
|
||||||
KT = TypeVar("KT")
|
KT = TypeVar("KT")
|
||||||
VT = TypeVar("VT")
|
VT = TypeVar("VT")
|
||||||
|
@ -124,7 +123,7 @@ class SkipList(Generic[KT, VT]):
|
||||||
|
|
||||||
return level
|
return level
|
||||||
|
|
||||||
def _locate_node(self, key) -> tuple[Optional[Node[KT, VT]], list[Node[KT, VT]]]:
|
def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]:
|
||||||
"""
|
"""
|
||||||
:param key: Searched key,
|
:param key: Searched key,
|
||||||
:return: Tuple with searched node (or None if given key is not present)
|
:return: Tuple with searched node (or None if given key is not present)
|
||||||
|
@ -222,7 +221,7 @@ class SkipList(Generic[KT, VT]):
|
||||||
else:
|
else:
|
||||||
update_node.forward[i] = new_node
|
update_node.forward[i] = new_node
|
||||||
|
|
||||||
def find(self, key: VT) -> Optional[VT]:
|
def find(self, key: VT) -> VT | None:
|
||||||
"""
|
"""
|
||||||
:param key: Search key.
|
:param key: Search key.
|
||||||
:return: Value associated with given key or None if given key is not present.
|
:return: Value associated with given key or None if given key is not present.
|
||||||
|
|
|
@ -1,5 +1,3 @@
|
||||||
from typing import Any, List
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
The Reverse Polish Nation also known as Polish postfix notation
|
The Reverse Polish Nation also known as Polish postfix notation
|
||||||
or simply postfix notation.
|
or simply postfix notation.
|
||||||
|
@ -8,6 +6,9 @@ Classic examples of simple stack implementations
|
||||||
Valid operators are +, -, *, /.
|
Valid operators are +, -, *, /.
|
||||||
Each operand may be an integer or another expression.
|
Each operand may be an integer or another expression.
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
def evaluate_postfix(postfix_notation: list) -> int:
|
def evaluate_postfix(postfix_notation: list) -> int:
|
||||||
|
@ -23,7 +24,7 @@ def evaluate_postfix(postfix_notation: list) -> int:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
operations = {"+", "-", "*", "/"}
|
operations = {"+", "-", "*", "/"}
|
||||||
stack: List[Any] = []
|
stack: list[Any] = []
|
||||||
|
|
||||||
for token in postfix_notation:
|
for token in postfix_notation:
|
||||||
if token in operations:
|
if token in operations:
|
||||||
|
|
|
@ -1,5 +1,7 @@
|
||||||
""" A Stack using a linked list like structure """
|
""" A Stack using a linked list like structure """
|
||||||
from typing import Any, Optional
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
class Node:
|
class Node:
|
||||||
|
@ -42,7 +44,7 @@ class LinkedStack:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.top: Optional[Node] = None
|
self.top: Node | None = None
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
node = self.top
|
node = self.top
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
class StackOverflowError(BaseException):
|
class StackOverflowError(BaseException):
|
||||||
|
@ -15,7 +15,7 @@ class Stack:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, limit: int = 10):
|
def __init__(self, limit: int = 10):
|
||||||
self.stack: List[int] = []
|
self.stack: list[int] = []
|
||||||
self.limit = limit
|
self.limit = limit
|
||||||
|
|
||||||
def __bool__(self) -> bool:
|
def __bool__(self) -> bool:
|
||||||
|
|
|
@ -12,8 +12,9 @@ There are other several other algorithms for the convex hull problem
|
||||||
which have not been implemented here, yet.
|
which have not been implemented here, yet.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Iterable, List, Set, Union
|
from typing import Iterable
|
||||||
|
|
||||||
|
|
||||||
class Point:
|
class Point:
|
||||||
|
@ -84,8 +85,8 @@ class Point:
|
||||||
|
|
||||||
|
|
||||||
def _construct_points(
|
def _construct_points(
|
||||||
list_of_tuples: Union[List[Point], List[List[float]], Iterable[List[float]]]
|
list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]],
|
||||||
) -> List[Point]:
|
) -> list[Point]:
|
||||||
"""
|
"""
|
||||||
constructs a list of points from an array-like object of numbers
|
constructs a list of points from an array-like object of numbers
|
||||||
|
|
||||||
|
@ -114,7 +115,7 @@ def _construct_points(
|
||||||
[]
|
[]
|
||||||
"""
|
"""
|
||||||
|
|
||||||
points: List[Point] = []
|
points: list[Point] = []
|
||||||
if list_of_tuples:
|
if list_of_tuples:
|
||||||
for p in list_of_tuples:
|
for p in list_of_tuples:
|
||||||
if isinstance(p, Point):
|
if isinstance(p, Point):
|
||||||
|
@ -130,7 +131,7 @@ def _construct_points(
|
||||||
return points
|
return points
|
||||||
|
|
||||||
|
|
||||||
def _validate_input(points: Union[List[Point], List[List[float]]]) -> List[Point]:
|
def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]:
|
||||||
"""
|
"""
|
||||||
validates an input instance before a convex-hull algorithms uses it
|
validates an input instance before a convex-hull algorithms uses it
|
||||||
|
|
||||||
|
@ -218,7 +219,7 @@ def _det(a: Point, b: Point, c: Point) -> float:
|
||||||
return det
|
return det
|
||||||
|
|
||||||
|
|
||||||
def convex_hull_bf(points: List[Point]) -> List[Point]:
|
def convex_hull_bf(points: list[Point]) -> list[Point]:
|
||||||
"""
|
"""
|
||||||
Constructs the convex hull of a set of 2D points using a brute force algorithm.
|
Constructs the convex hull of a set of 2D points using a brute force algorithm.
|
||||||
The algorithm basically considers all combinations of points (i, j) and uses the
|
The algorithm basically considers all combinations of points (i, j) and uses the
|
||||||
|
@ -291,7 +292,7 @@ def convex_hull_bf(points: List[Point]) -> List[Point]:
|
||||||
return sorted(convex_set)
|
return sorted(convex_set)
|
||||||
|
|
||||||
|
|
||||||
def convex_hull_recursive(points: List[Point]) -> List[Point]:
|
def convex_hull_recursive(points: list[Point]) -> list[Point]:
|
||||||
"""
|
"""
|
||||||
Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy
|
Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy
|
||||||
The algorithm exploits the geometric properties of the problem by repeatedly
|
The algorithm exploits the geometric properties of the problem by repeatedly
|
||||||
|
@ -362,7 +363,7 @@ def convex_hull_recursive(points: List[Point]) -> List[Point]:
|
||||||
|
|
||||||
|
|
||||||
def _construct_hull(
|
def _construct_hull(
|
||||||
points: List[Point], left: Point, right: Point, convex_set: Set[Point]
|
points: list[Point], left: Point, right: Point, convex_set: set[Point]
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
@ -405,7 +406,7 @@ def _construct_hull(
|
||||||
_construct_hull(candidate_points, extreme_point, right, convex_set)
|
_construct_hull(candidate_points, extreme_point, right, convex_set)
|
||||||
|
|
||||||
|
|
||||||
def convex_hull_melkman(points: List[Point]) -> List[Point]:
|
def convex_hull_melkman(points: list[Point]) -> list[Point]:
|
||||||
"""
|
"""
|
||||||
Constructs the convex hull of a set of 2D points using the melkman algorithm.
|
Constructs the convex hull of a set of 2D points using the melkman algorithm.
|
||||||
The algorithm works by iteratively inserting points of a simple polygonal chain
|
The algorithm works by iteratively inserting points of a simple polygonal chain
|
||||||
|
|
|
@ -8,8 +8,9 @@ This is a divide and conquer algorithm that can find a solution in O(n) time.
|
||||||
For more information of this algorithm:
|
For more information of this algorithm:
|
||||||
https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf
|
https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from random import choice
|
from random import choice
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
def random_pivot(lst):
|
def random_pivot(lst):
|
||||||
|
@ -21,7 +22,7 @@ def random_pivot(lst):
|
||||||
return choice(lst)
|
return choice(lst)
|
||||||
|
|
||||||
|
|
||||||
def kth_number(lst: List[int], k: int) -> int:
|
def kth_number(lst: list[int], k: int) -> int:
|
||||||
"""
|
"""
|
||||||
Return the kth smallest number in lst.
|
Return the kth smallest number in lst.
|
||||||
>>> kth_number([2, 1, 3, 4, 5], 3)
|
>>> kth_number([2, 1, 3, 4, 5], 3)
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def merge(left_half: List, right_half: List) -> List:
|
def merge(left_half: list, right_half: list) -> list:
|
||||||
"""Helper function for mergesort.
|
"""Helper function for mergesort.
|
||||||
|
|
||||||
>>> left_half = [-2]
|
>>> left_half = [-2]
|
||||||
|
@ -57,7 +57,7 @@ def merge(left_half: List, right_half: List) -> List:
|
||||||
return sorted_array
|
return sorted_array
|
||||||
|
|
||||||
|
|
||||||
def merge_sort(array: List) -> List:
|
def merge_sort(array: list) -> list:
|
||||||
"""Returns a list of sorted array elements using merge sort.
|
"""Returns a list of sorted array elements using merge sort.
|
||||||
|
|
||||||
>>> from random import shuffle
|
>>> from random import shuffle
|
||||||
|
|
|
@ -7,10 +7,10 @@ to find the maximum of the array.
|
||||||
(From Kleinberg and Tardos. Algorithm Design.
|
(From Kleinberg and Tardos. Algorithm Design.
|
||||||
Addison Wesley 2006: Chapter 5 Solved Exercise 1)
|
Addison Wesley 2006: Chapter 5 Solved Exercise 1)
|
||||||
"""
|
"""
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def peak(lst: List[int]) -> int:
|
def peak(lst: list[int]) -> int:
|
||||||
"""
|
"""
|
||||||
Return the peak value of `lst`.
|
Return the peak value of `lst`.
|
||||||
>>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1])
|
>>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1])
|
||||||
|
|
|
@ -1,9 +1,10 @@
|
||||||
# https://en.m.wikipedia.org/wiki/Electric_power
|
# https://en.m.wikipedia.org/wiki/Electric_power
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from collections import namedtuple
|
from collections import namedtuple
|
||||||
from typing import Tuple
|
|
||||||
|
|
||||||
|
|
||||||
def electric_power(voltage: float, current: float, power: float) -> Tuple:
|
def electric_power(voltage: float, current: float, power: float) -> tuple:
|
||||||
"""
|
"""
|
||||||
This function can calculate any one of the three (voltage, current, power),
|
This function can calculate any one of the three (voltage, current, power),
|
||||||
fundamental value of electrical system.
|
fundamental value of electrical system.
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
# https://en.wikipedia.org/wiki/Ohm%27s_law
|
# https://en.wikipedia.org/wiki/Ohm%27s_law
|
||||||
from typing import Dict
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def ohms_law(voltage: float, current: float, resistance: float) -> Dict[str, float]:
|
def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]:
|
||||||
"""
|
"""
|
||||||
Apply Ohm's Law, on any two given electrical values, which can be voltage, current,
|
Apply Ohm's Law, on any two given electrical values, which can be voltage, current,
|
||||||
and resistance, and then in a Python dict return name/value pair of the zero value.
|
and resistance, and then in a Python dict return name/value pair of the zero value.
|
||||||
|
|
|
@ -13,7 +13,7 @@ def initialize_unweighted_directed_graph(
|
||||||
graph[i + 1] = []
|
graph[i + 1] = []
|
||||||
|
|
||||||
for e in range(edge_count):
|
for e in range(edge_count):
|
||||||
x, y = [int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")]
|
x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> "))
|
||||||
graph[x].append(y)
|
graph[x].append(y)
|
||||||
return graph
|
return graph
|
||||||
|
|
||||||
|
@ -26,7 +26,7 @@ def initialize_unweighted_undirected_graph(
|
||||||
graph[i + 1] = []
|
graph[i + 1] = []
|
||||||
|
|
||||||
for e in range(edge_count):
|
for e in range(edge_count):
|
||||||
x, y = [int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")]
|
x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> "))
|
||||||
graph[x].append(y)
|
graph[x].append(y)
|
||||||
graph[y].append(x)
|
graph[y].append(x)
|
||||||
return graph
|
return graph
|
||||||
|
@ -40,14 +40,14 @@ def initialize_weighted_undirected_graph(
|
||||||
graph[i + 1] = []
|
graph[i + 1] = []
|
||||||
|
|
||||||
for e in range(edge_count):
|
for e in range(edge_count):
|
||||||
x, y, w = [int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> ")]
|
x, y, w = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> "))
|
||||||
graph[x].append((y, w))
|
graph[x].append((y, w))
|
||||||
graph[y].append((x, w))
|
graph[y].append((x, w))
|
||||||
return graph
|
return graph
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
n, m = [int(i) for i in _input("Number of nodes and edges: ")]
|
n, m = (int(i) for i in _input("Number of nodes and edges: "))
|
||||||
|
|
||||||
graph_choice = int(
|
graph_choice = int(
|
||||||
_input(
|
_input(
|
||||||
|
|
|
@ -11,7 +11,7 @@ def check_negative_cycle(
|
||||||
graph: list[dict[str, int]], distance: list[float], edge_count: int
|
graph: list[dict[str, int]], distance: list[float], edge_count: int
|
||||||
):
|
):
|
||||||
for j in range(edge_count):
|
for j in range(edge_count):
|
||||||
u, v, w = [graph[j][k] for k in ["src", "dst", "weight"]]
|
u, v, w = (graph[j][k] for k in ["src", "dst", "weight"])
|
||||||
if distance[u] != float("inf") and distance[u] + w < distance[v]:
|
if distance[u] != float("inf") and distance[u] + w < distance[v]:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
@ -38,7 +38,7 @@ def bellman_ford(
|
||||||
|
|
||||||
for i in range(vertex_count - 1):
|
for i in range(vertex_count - 1):
|
||||||
for j in range(edge_count):
|
for j in range(edge_count):
|
||||||
u, v, w = [graph[j][k] for k in ["src", "dst", "weight"]]
|
u, v, w = (graph[j][k] for k in ["src", "dst", "weight"])
|
||||||
|
|
||||||
if distance[u] != float("inf") and distance[u] + w < distance[v]:
|
if distance[u] != float("inf") and distance[u] + w < distance[v]:
|
||||||
distance[v] = distance[u] + w
|
distance[v] = distance[u] + w
|
||||||
|
@ -62,10 +62,10 @@ if __name__ == "__main__":
|
||||||
|
|
||||||
for i in range(E):
|
for i in range(E):
|
||||||
print("Edge ", i + 1)
|
print("Edge ", i + 1)
|
||||||
src, dest, weight = [
|
src, dest, weight = (
|
||||||
int(x)
|
int(x)
|
||||||
for x in input("Enter source, destination, weight: ").strip().split(" ")
|
for x in input("Enter source, destination, weight: ").strip().split(" ")
|
||||||
]
|
)
|
||||||
graph[i] = {"src": src, "dst": dest, "weight": weight}
|
graph[i] = {"src": src, "dst": dest, "weight": weight}
|
||||||
|
|
||||||
source = int(input("\nEnter shortest path source:").strip())
|
source = int(input("\nEnter shortest path source:").strip())
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
from collections import deque
|
|
||||||
from collections.abc import Iterator
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import Optional, Union
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra.
|
Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra.
|
||||||
0-1-graph is the weighted graph with the weights equal to 0 or 1.
|
0-1-graph is the weighted graph with the weights equal to 0 or 1.
|
||||||
Link: https://codeforces.com/blog/entry/22276
|
Link: https://codeforces.com/blog/entry/22276
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections import deque
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
|
@ -59,7 +59,7 @@ class AdjacencyList:
|
||||||
|
|
||||||
self._graph[from_vertex].append(Edge(to_vertex, weight))
|
self._graph[from_vertex].append(Edge(to_vertex, weight))
|
||||||
|
|
||||||
def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> Optional[int]:
|
def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int | None:
|
||||||
"""
|
"""
|
||||||
Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.
|
Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.
|
||||||
1 1 1
|
1 1 1
|
||||||
|
@ -107,7 +107,7 @@ class AdjacencyList:
|
||||||
ValueError: No path from start_vertex to finish_vertex.
|
ValueError: No path from start_vertex to finish_vertex.
|
||||||
"""
|
"""
|
||||||
queue = deque([start_vertex])
|
queue = deque([start_vertex])
|
||||||
distances: list[Union[int, None]] = [None] * self.size
|
distances: list[int | None] = [None] * self.size
|
||||||
distances[start_vertex] = 0
|
distances[start_vertex] = 0
|
||||||
|
|
||||||
while queue:
|
while queue:
|
||||||
|
|
|
@ -1,15 +1,12 @@
|
||||||
"""
|
"""
|
||||||
https://en.wikipedia.org/wiki/Bidirectional_search
|
https://en.wikipedia.org/wiki/Bidirectional_search
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import time
|
import time
|
||||||
from math import sqrt
|
from math import sqrt
|
||||||
|
|
||||||
# 1 for manhattan, 0 for euclidean
|
# 1 for manhattan, 0 for euclidean
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
HEURISTIC = 0
|
HEURISTIC = 0
|
||||||
|
|
||||||
grid = [
|
grid = [
|
||||||
|
@ -50,7 +47,7 @@ class Node:
|
||||||
goal_x: int,
|
goal_x: int,
|
||||||
goal_y: int,
|
goal_y: int,
|
||||||
g_cost: int,
|
g_cost: int,
|
||||||
parent: Optional[Node],
|
parent: Node | None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self.pos_x = pos_x
|
self.pos_x = pos_x
|
||||||
self.pos_y = pos_y
|
self.pos_y = pos_y
|
||||||
|
@ -157,7 +154,7 @@ class AStar:
|
||||||
)
|
)
|
||||||
return successors
|
return successors
|
||||||
|
|
||||||
def retrace_path(self, node: Optional[Node]) -> list[TPosition]:
|
def retrace_path(self, node: Node | None) -> list[TPosition]:
|
||||||
"""
|
"""
|
||||||
Retrace the path from parents to parents until start node
|
Retrace the path from parents to parents until start node
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,11 +1,9 @@
|
||||||
"""
|
"""
|
||||||
https://en.wikipedia.org/wiki/Bidirectional_search
|
https://en.wikipedia.org/wiki/Bidirectional_search
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import time
|
import time
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
Path = list[tuple[int, int]]
|
Path = list[tuple[int, int]]
|
||||||
|
|
||||||
|
@ -24,7 +22,7 @@ delta = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
|
||||||
|
|
||||||
class Node:
|
class Node:
|
||||||
def __init__(
|
def __init__(
|
||||||
self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, parent: Optional[Node]
|
self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, parent: Node | None
|
||||||
):
|
):
|
||||||
self.pos_x = pos_x
|
self.pos_x = pos_x
|
||||||
self.pos_y = pos_y
|
self.pos_y = pos_y
|
||||||
|
@ -57,7 +55,7 @@ class BreadthFirstSearch:
|
||||||
self.node_queue = [self.start]
|
self.node_queue = [self.start]
|
||||||
self.reached = False
|
self.reached = False
|
||||||
|
|
||||||
def search(self) -> Optional[Path]:
|
def search(self) -> Path | None:
|
||||||
while self.node_queue:
|
while self.node_queue:
|
||||||
current_node = self.node_queue.pop(0)
|
current_node = self.node_queue.pop(0)
|
||||||
|
|
||||||
|
@ -93,7 +91,7 @@ class BreadthFirstSearch:
|
||||||
)
|
)
|
||||||
return successors
|
return successors
|
||||||
|
|
||||||
def retrace_path(self, node: Optional[Node]) -> Path:
|
def retrace_path(self, node: Node | None) -> Path:
|
||||||
"""
|
"""
|
||||||
Retrace the path from parents to parents until start node
|
Retrace the path from parents to parents until start node
|
||||||
"""
|
"""
|
||||||
|
@ -125,7 +123,7 @@ class BidirectionalBreadthFirstSearch:
|
||||||
self.bwd_bfs = BreadthFirstSearch(goal, start)
|
self.bwd_bfs = BreadthFirstSearch(goal, start)
|
||||||
self.reached = False
|
self.reached = False
|
||||||
|
|
||||||
def search(self) -> Optional[Path]:
|
def search(self) -> Path | None:
|
||||||
while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
|
while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
|
||||||
current_fwd_node = self.fwd_bfs.node_queue.pop(0)
|
current_fwd_node = self.fwd_bfs.node_queue.pop(0)
|
||||||
current_bwd_node = self.bwd_bfs.node_queue.pop(0)
|
current_bwd_node = self.bwd_bfs.node_queue.pop(0)
|
||||||
|
|
|
@ -1,13 +1,12 @@
|
||||||
#!/usr/bin/python
|
#!/usr/bin/python
|
||||||
|
|
||||||
""" Author: OMKAR PATHAK """
|
""" Author: OMKAR PATHAK """
|
||||||
|
from __future__ import annotations
|
||||||
from typing import Dict, List, Set
|
|
||||||
|
|
||||||
|
|
||||||
class Graph:
|
class Graph:
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.vertices: Dict[int, List[int]] = {}
|
self.vertices: dict[int, list[int]] = {}
|
||||||
|
|
||||||
def print_graph(self) -> None:
|
def print_graph(self) -> None:
|
||||||
"""
|
"""
|
||||||
|
@ -35,7 +34,7 @@ class Graph:
|
||||||
else:
|
else:
|
||||||
self.vertices[from_vertex] = [to_vertex]
|
self.vertices[from_vertex] = [to_vertex]
|
||||||
|
|
||||||
def bfs(self, start_vertex: int) -> Set[int]:
|
def bfs(self, start_vertex: int) -> set[int]:
|
||||||
"""
|
"""
|
||||||
>>> g = Graph()
|
>>> g = Graph()
|
||||||
>>> g.add_edge(0, 1)
|
>>> g.add_edge(0, 1)
|
||||||
|
|
|
@ -3,8 +3,6 @@ from a given source node to a target node in an unweighted graph.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
graph = {
|
graph = {
|
||||||
"A": ["B", "C", "E"],
|
"A": ["B", "C", "E"],
|
||||||
"B": ["A", "D", "E"],
|
"B": ["A", "D", "E"],
|
||||||
|
@ -24,7 +22,7 @@ class Graph:
|
||||||
"""
|
"""
|
||||||
self.graph = graph
|
self.graph = graph
|
||||||
# mapping node to its parent in resulting breadth first tree
|
# mapping node to its parent in resulting breadth first tree
|
||||||
self.parent: dict[str, Optional[str]] = {}
|
self.parent: dict[str, str | None] = {}
|
||||||
self.source_vertex = source_vertex
|
self.source_vertex = source_vertex
|
||||||
|
|
||||||
def breath_first_search(self) -> None:
|
def breath_first_search(self) -> None:
|
||||||
|
|
|
@ -1,11 +1,8 @@
|
||||||
"""Non recursive implementation of a DFS algorithm."""
|
"""Non recursive implementation of a DFS algorithm."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Set
|
|
||||||
|
|
||||||
|
def depth_first_search(graph: dict, start: str) -> set[str]:
|
||||||
def depth_first_search(graph: dict, start: str) -> Set[str]:
|
|
||||||
"""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 start: starting vertex as a string
|
:param start: starting vertex as a string
|
||||||
|
|
|
@ -4,8 +4,6 @@ https://en.wikipedia.org/wiki/Best-first_search#Greedy_BFS
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
Path = list[tuple[int, int]]
|
Path = list[tuple[int, int]]
|
||||||
|
|
||||||
grid = [
|
grid = [
|
||||||
|
@ -44,7 +42,7 @@ class Node:
|
||||||
goal_x: int,
|
goal_x: int,
|
||||||
goal_y: int,
|
goal_y: int,
|
||||||
g_cost: float,
|
g_cost: float,
|
||||||
parent: Optional[Node],
|
parent: Node | None,
|
||||||
):
|
):
|
||||||
self.pos_x = pos_x
|
self.pos_x = pos_x
|
||||||
self.pos_y = pos_y
|
self.pos_y = pos_y
|
||||||
|
@ -93,7 +91,7 @@ class GreedyBestFirst:
|
||||||
|
|
||||||
self.reached = False
|
self.reached = False
|
||||||
|
|
||||||
def search(self) -> Optional[Path]:
|
def search(self) -> Path | None:
|
||||||
"""
|
"""
|
||||||
Search for the path,
|
Search for the path,
|
||||||
if a path is not found, only the starting position is returned
|
if a path is not found, only the starting position is returned
|
||||||
|
@ -156,7 +154,7 @@ class GreedyBestFirst:
|
||||||
)
|
)
|
||||||
return successors
|
return successors
|
||||||
|
|
||||||
def retrace_path(self, node: Optional[Node]) -> Path:
|
def retrace_path(self, node: Node | None) -> Path:
|
||||||
"""
|
"""
|
||||||
Retrace the path from parents to parents until start node
|
Retrace the path from parents to parents until start node
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -40,7 +40,7 @@ if __name__ == "__main__": # pragma: no cover
|
||||||
edges = []
|
edges = []
|
||||||
|
|
||||||
for _ in range(num_edges):
|
for _ in range(num_edges):
|
||||||
node1, node2, cost = [int(x) for x in input().strip().split()]
|
node1, node2, cost = (int(x) for x in input().strip().split())
|
||||||
edges.append((node1, node2, cost))
|
edges.append((node1, node2, cost))
|
||||||
|
|
||||||
kruskal(num_nodes, edges)
|
kruskal(num_nodes, edges)
|
||||||
|
|
|
@ -6,9 +6,10 @@ edges in the tree is minimized. The algorithm operates by building this tree one
|
||||||
at a time, from an arbitrary starting vertex, at each step adding the cheapest possible
|
at a time, from an arbitrary starting vertex, at each step adding the cheapest possible
|
||||||
connection from the tree to another vertex.
|
connection from the tree to another vertex.
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from sys import maxsize
|
from sys import maxsize
|
||||||
from typing import Generic, Optional, TypeVar
|
from typing import Generic, TypeVar
|
||||||
|
|
||||||
T = TypeVar("T")
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
@ -219,7 +220,7 @@ class GraphUndirectedWeighted(Generic[T]):
|
||||||
|
|
||||||
def prims_algo(
|
def prims_algo(
|
||||||
graph: GraphUndirectedWeighted[T],
|
graph: GraphUndirectedWeighted[T],
|
||||||
) -> tuple[dict[T, int], dict[T, Optional[T]]]:
|
) -> tuple[dict[T, int], dict[T, T | None]]:
|
||||||
"""
|
"""
|
||||||
>>> graph = GraphUndirectedWeighted()
|
>>> graph = GraphUndirectedWeighted()
|
||||||
|
|
||||||
|
@ -240,7 +241,7 @@ def prims_algo(
|
||||||
"""
|
"""
|
||||||
# prim's algorithm for minimum spanning tree
|
# prim's algorithm for minimum spanning tree
|
||||||
dist: dict[T, int] = {node: maxsize for node in graph.connections}
|
dist: dict[T, int] = {node: maxsize for node in graph.connections}
|
||||||
parent: dict[T, Optional[T]] = {node: None for node in graph.connections}
|
parent: dict[T, T | None] = {node: None for node in graph.connections}
|
||||||
|
|
||||||
priority_queue: MinPriorityQueue[T] = MinPriorityQueue()
|
priority_queue: MinPriorityQueue[T] = MinPriorityQueue()
|
||||||
for node, weight in dist.items():
|
for node, weight in dist.items():
|
||||||
|
|
|
@ -43,7 +43,7 @@ def page_rank(nodes, limit=3, d=0.85):
|
||||||
print(f"======= Iteration {i + 1} =======")
|
print(f"======= Iteration {i + 1} =======")
|
||||||
for j, node in enumerate(nodes):
|
for j, node in enumerate(nodes):
|
||||||
ranks[node.name] = (1 - d) + d * sum(
|
ranks[node.name] = (1 - d) + d * sum(
|
||||||
[ranks[ib] / outbounds[ib] for ib in node.inbound]
|
ranks[ib] / outbounds[ib] for ib in node.inbound
|
||||||
)
|
)
|
||||||
print(ranks)
|
print(ranks)
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def dfs(u):
|
def dfs(u):
|
||||||
|
@ -39,16 +39,16 @@ if __name__ == "__main__":
|
||||||
# n - no of nodes, m - no of edges
|
# n - no of nodes, m - no of edges
|
||||||
n, m = list(map(int, input().strip().split()))
|
n, m = list(map(int, input().strip().split()))
|
||||||
|
|
||||||
graph: List[List[int]] = [[] for i in range(n)] # graph
|
graph: list[list[int]] = [[] for i in range(n)] # graph
|
||||||
reversedGraph: List[List[int]] = [[] for i in range(n)] # reversed graph
|
reversedGraph: list[list[int]] = [[] for i in range(n)] # reversed graph
|
||||||
# input graph data (edges)
|
# input graph data (edges)
|
||||||
for i in range(m):
|
for i in range(m):
|
||||||
u, v = list(map(int, input().strip().split()))
|
u, v = list(map(int, input().strip().split()))
|
||||||
graph[u].append(v)
|
graph[u].append(v)
|
||||||
reversedGraph[v].append(u)
|
reversedGraph[v].append(u)
|
||||||
|
|
||||||
stack: List[int] = []
|
stack: list[int] = []
|
||||||
visit: List[bool] = [False] * n
|
visit: list[bool] = [False] * n
|
||||||
scc: List[int] = []
|
scc: list[int] = []
|
||||||
component: List[int] = []
|
component: list[int] = []
|
||||||
print(kosaraju())
|
print(kosaraju())
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
""" Luhn Algorithm """
|
""" Luhn Algorithm """
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def is_luhn(string: str) -> bool:
|
def is_luhn(string: str) -> bool:
|
||||||
|
@ -17,9 +17,9 @@ def is_luhn(string: str) -> bool:
|
||||||
[False, False, False, True, False, False, False, False, False, False]
|
[False, False, False, True, False, False, False, False, False, False]
|
||||||
"""
|
"""
|
||||||
check_digit: int
|
check_digit: int
|
||||||
_vector: List[str] = list(string)
|
_vector: list[str] = list(string)
|
||||||
__vector, check_digit = _vector[:-1], int(_vector[-1])
|
__vector, check_digit = _vector[:-1], int(_vector[-1])
|
||||||
vector: List[int] = [int(digit) for digit in __vector]
|
vector: list[int] = [int(digit) for digit in __vector]
|
||||||
|
|
||||||
vector.reverse()
|
vector.reverse()
|
||||||
for i, digit in enumerate(vector):
|
for i, digit in enumerate(vector):
|
||||||
|
|
|
@ -1,11 +1,10 @@
|
||||||
from typing import List
|
|
||||||
|
|
||||||
""" A naive recursive implementation of 0-1 Knapsack Problem
|
""" A naive recursive implementation of 0-1 Knapsack Problem
|
||||||
https://en.wikipedia.org/wiki/Knapsack_problem
|
https://en.wikipedia.org/wiki/Knapsack_problem
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def knapsack(capacity: int, weights: List[int], values: List[int], counter: int) -> int:
|
def knapsack(capacity: int, weights: list[int], values: list[int], counter: int) -> int:
|
||||||
"""
|
"""
|
||||||
Returns the maximum value that can be put in a knapsack of a capacity cap,
|
Returns the maximum value that can be put in a knapsack of a capacity cap,
|
||||||
whereby each weight w has a specific value val.
|
whereby each weight w has a specific value val.
|
||||||
|
|
|
@ -18,11 +18,11 @@ Overview:
|
||||||
- function squareZeroMatrix(N)
|
- function squareZeroMatrix(N)
|
||||||
- function randomMatrix(W,H,a,b)
|
- function randomMatrix(W,H,a,b)
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import math
|
import math
|
||||||
import random
|
import random
|
||||||
from typing import Collection, Optional, Union, overload
|
from typing import Collection, overload
|
||||||
|
|
||||||
|
|
||||||
class Vector:
|
class Vector:
|
||||||
|
@ -46,7 +46,7 @@ class Vector:
|
||||||
TODO: compare-operator
|
TODO: compare-operator
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, components: Optional[Collection[float]] = None) -> None:
|
def __init__(self, components: Collection[float] | None = None) -> None:
|
||||||
"""
|
"""
|
||||||
input: components or nothing
|
input: components or nothing
|
||||||
simple constructor for init the vector
|
simple constructor for init the vector
|
||||||
|
@ -97,7 +97,7 @@ class Vector:
|
||||||
summe += c ** 2
|
summe += c ** 2
|
||||||
return math.sqrt(summe)
|
return math.sqrt(summe)
|
||||||
|
|
||||||
def __add__(self, other: "Vector") -> "Vector":
|
def __add__(self, other: Vector) -> Vector:
|
||||||
"""
|
"""
|
||||||
input: other vector
|
input: other vector
|
||||||
assumes: other vector has the same size
|
assumes: other vector has the same size
|
||||||
|
@ -110,7 +110,7 @@ class Vector:
|
||||||
else:
|
else:
|
||||||
raise Exception("must have the same size")
|
raise Exception("must have the same size")
|
||||||
|
|
||||||
def __sub__(self, other: "Vector") -> "Vector":
|
def __sub__(self, other: Vector) -> Vector:
|
||||||
"""
|
"""
|
||||||
input: other vector
|
input: other vector
|
||||||
assumes: other vector has the same size
|
assumes: other vector has the same size
|
||||||
|
@ -124,14 +124,14 @@ class Vector:
|
||||||
raise Exception("must have the same size")
|
raise Exception("must have the same size")
|
||||||
|
|
||||||
@overload
|
@overload
|
||||||
def __mul__(self, other: float) -> "Vector":
|
def __mul__(self, other: float) -> Vector:
|
||||||
...
|
...
|
||||||
|
|
||||||
@overload
|
@overload
|
||||||
def __mul__(self, other: "Vector") -> float:
|
def __mul__(self, other: Vector) -> float:
|
||||||
...
|
...
|
||||||
|
|
||||||
def __mul__(self, other: Union[float, "Vector"]) -> Union[float, "Vector"]:
|
def __mul__(self, other: float | Vector) -> float | Vector:
|
||||||
"""
|
"""
|
||||||
mul implements the scalar multiplication
|
mul implements the scalar multiplication
|
||||||
and the dot-product
|
and the dot-product
|
||||||
|
@ -148,7 +148,7 @@ class Vector:
|
||||||
else: # error case
|
else: # error case
|
||||||
raise Exception("invalid operand!")
|
raise Exception("invalid operand!")
|
||||||
|
|
||||||
def copy(self) -> "Vector":
|
def copy(self) -> Vector:
|
||||||
"""
|
"""
|
||||||
copies this vector and returns it.
|
copies this vector and returns it.
|
||||||
"""
|
"""
|
||||||
|
@ -313,14 +313,14 @@ class Matrix:
|
||||||
raise Exception("matrix is not square")
|
raise Exception("matrix is not square")
|
||||||
|
|
||||||
@overload
|
@overload
|
||||||
def __mul__(self, other: float) -> "Matrix":
|
def __mul__(self, other: float) -> Matrix:
|
||||||
...
|
...
|
||||||
|
|
||||||
@overload
|
@overload
|
||||||
def __mul__(self, other: Vector) -> Vector:
|
def __mul__(self, other: Vector) -> Vector:
|
||||||
...
|
...
|
||||||
|
|
||||||
def __mul__(self, other: Union[float, Vector]) -> Union[Vector, "Matrix"]:
|
def __mul__(self, other: float | Vector) -> Vector | Matrix:
|
||||||
"""
|
"""
|
||||||
implements the matrix-vector multiplication.
|
implements the matrix-vector multiplication.
|
||||||
implements the matrix-scalar multiplication
|
implements the matrix-scalar multiplication
|
||||||
|
@ -347,7 +347,7 @@ class Matrix:
|
||||||
]
|
]
|
||||||
return Matrix(matrix, self.__width, self.__height)
|
return Matrix(matrix, self.__width, self.__height)
|
||||||
|
|
||||||
def __add__(self, other: "Matrix") -> "Matrix":
|
def __add__(self, other: Matrix) -> Matrix:
|
||||||
"""
|
"""
|
||||||
implements the matrix-addition.
|
implements the matrix-addition.
|
||||||
"""
|
"""
|
||||||
|
@ -362,7 +362,7 @@ class Matrix:
|
||||||
else:
|
else:
|
||||||
raise Exception("matrix must have the same dimension!")
|
raise Exception("matrix must have the same dimension!")
|
||||||
|
|
||||||
def __sub__(self, other: "Matrix") -> "Matrix":
|
def __sub__(self, other: Matrix) -> Matrix:
|
||||||
"""
|
"""
|
||||||
implements the matrix-subtraction.
|
implements the matrix-subtraction.
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -7,8 +7,9 @@ returns a list containing two data for each vector:
|
||||||
1. the nearest vector
|
1. the nearest vector
|
||||||
2. distance between the vector and the nearest vector (float)
|
2. distance between the vector and the nearest vector (float)
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import math
|
import math
|
||||||
from typing import List, Union
|
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
@ -33,7 +34,7 @@ def euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float:
|
||||||
|
|
||||||
def similarity_search(
|
def similarity_search(
|
||||||
dataset: np.ndarray, value_array: np.ndarray
|
dataset: np.ndarray, value_array: np.ndarray
|
||||||
) -> List[List[Union[List[float], float]]]:
|
) -> list[list[list[float] | float]]:
|
||||||
"""
|
"""
|
||||||
:param dataset: Set containing the vectors. Should be ndarray.
|
:param dataset: Set containing the vectors. Should be ndarray.
|
||||||
:param value_array: vector/vectors we want to know the nearest vector from dataset.
|
:param value_array: vector/vectors we want to know the nearest vector from dataset.
|
||||||
|
|
|
@ -1,14 +1,15 @@
|
||||||
"""
|
"""
|
||||||
Approximates the area under the curve using the trapezoidal rule
|
Approximates the area under the curve using the trapezoidal rule
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Callable, Union
|
from typing import Callable
|
||||||
|
|
||||||
|
|
||||||
def trapezoidal_area(
|
def trapezoidal_area(
|
||||||
fnc: Callable[[Union[int, float]], Union[int, float]],
|
fnc: Callable[[int | float], int | float],
|
||||||
x_start: Union[int, float],
|
x_start: int | float,
|
||||||
x_end: Union[int, float],
|
x_end: int | float,
|
||||||
steps: int = 100,
|
steps: int = 100,
|
||||||
) -> float:
|
) -> float:
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def mean(nums: List) -> float:
|
def mean(nums: list) -> float:
|
||||||
"""
|
"""
|
||||||
Find mean of a list of numbers.
|
Find mean of a list of numbers.
|
||||||
Wiki: https://en.wikipedia.org/wiki/Mean
|
Wiki: https://en.wikipedia.org/wiki/Mean
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
from typing import Union
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def median(nums: list) -> Union[int, float]:
|
def median(nums: list) -> int | float:
|
||||||
"""
|
"""
|
||||||
Find median of a list of numbers.
|
Find median of a list of numbers.
|
||||||
Wiki: https://en.wikipedia.org/wiki/Median
|
Wiki: https://en.wikipedia.org/wiki/Median
|
||||||
|
|
|
@ -68,7 +68,7 @@ def calculate_prob(text: str) -> None:
|
||||||
my_fir_sum += prob * math.log2(prob) # entropy formula.
|
my_fir_sum += prob * math.log2(prob) # entropy formula.
|
||||||
|
|
||||||
# print entropy
|
# print entropy
|
||||||
print("{:.1f}".format(round(-1 * my_fir_sum)))
|
print(f"{round(-1 * my_fir_sum):.1f}")
|
||||||
|
|
||||||
# two len string
|
# two len string
|
||||||
all_sum = sum(two_char_strings.values())
|
all_sum = sum(two_char_strings.values())
|
||||||
|
@ -83,10 +83,10 @@ def calculate_prob(text: str) -> None:
|
||||||
my_sec_sum += prob * math.log2(prob)
|
my_sec_sum += prob * math.log2(prob)
|
||||||
|
|
||||||
# print second entropy
|
# print second entropy
|
||||||
print("{:.1f}".format(round(-1 * my_sec_sum)))
|
print(f"{round(-1 * my_sec_sum):.1f}")
|
||||||
|
|
||||||
# print the difference between them
|
# print the difference between them
|
||||||
print("{:.1f}".format(round((-1 * my_sec_sum) - (-1 * my_fir_sum))))
|
print(f"{round((-1 * my_sec_sum) - (-1 * my_fir_sum)):.1f}")
|
||||||
|
|
||||||
|
|
||||||
def analyze_text(text: str) -> tuple[dict, dict]:
|
def analyze_text(text: str) -> tuple[dict, dict]:
|
||||||
|
|
|
@ -1,3 +1,5 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Iterable, Union
|
from typing import Iterable, Union
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
|
@ -12,12 +12,12 @@ https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
|
||||||
# @Email: silentcat@protonmail.com
|
# @Email: silentcat@protonmail.com
|
||||||
# @Last modified by: pikulet
|
# @Last modified by: pikulet
|
||||||
# @Last modified time: 2020-10-02
|
# @Last modified time: 2020-10-02
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
from typing import Tuple
|
|
||||||
|
|
||||||
|
|
||||||
def extended_euclidean_algorithm(a: int, b: int) -> Tuple[int, int]:
|
def extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]:
|
||||||
"""
|
"""
|
||||||
Extended Euclidean Algorithm.
|
Extended Euclidean Algorithm.
|
||||||
|
|
||||||
|
|
|
@ -37,7 +37,7 @@ def exactPrimeFactorCount(n):
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
n = 51242183
|
n = 51242183
|
||||||
print(f"The number of distinct prime factors is/are {exactPrimeFactorCount(n)}")
|
print(f"The number of distinct prime factors is/are {exactPrimeFactorCount(n)}")
|
||||||
print("The value of log(log(n)) is {:.4f}".format(math.log(math.log(n))))
|
print(f"The value of log(log(n)) is {math.log(math.log(n)):.4f}")
|
||||||
|
|
||||||
"""
|
"""
|
||||||
The number of distinct prime factors is/are 3
|
The number of distinct prime factors is/are 3
|
||||||
|
|
|
@ -1,11 +1,13 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import math
|
import math
|
||||||
from typing import Callable, Union
|
from typing import Callable
|
||||||
|
|
||||||
|
|
||||||
def line_length(
|
def line_length(
|
||||||
fnc: Callable[[Union[int, float]], Union[int, float]],
|
fnc: Callable[[int | float], int | float],
|
||||||
x_start: Union[int, float],
|
x_start: int | float,
|
||||||
x_end: Union[int, float],
|
x_end: int | float,
|
||||||
steps: int = 100,
|
steps: int = 100,
|
||||||
) -> float:
|
) -> float:
|
||||||
|
|
||||||
|
|
|
@ -6,10 +6,10 @@ Instead of using a nested for loop, in a Brute force approach we will use a tech
|
||||||
called 'Window sliding technique' where the nested loops can be converted to a single
|
called 'Window sliding technique' where the nested loops can be converted to a single
|
||||||
loop to reduce time complexity.
|
loop to reduce time complexity.
|
||||||
"""
|
"""
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def max_sum_in_array(array: List[int], k: int) -> int:
|
def max_sum_in_array(array: list[int], k: int) -> int:
|
||||||
"""
|
"""
|
||||||
Returns the maximum sum of k consecutive elements
|
Returns the maximum sum of k consecutive elements
|
||||||
>>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
|
>>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def median_of_two_arrays(nums1: List[float], nums2: List[float]) -> float:
|
def median_of_two_arrays(nums1: list[float], nums2: list[float]) -> float:
|
||||||
"""
|
"""
|
||||||
>>> median_of_two_arrays([1, 2], [3])
|
>>> median_of_two_arrays([1, 2], [3])
|
||||||
2
|
2
|
||||||
|
|
|
@ -1,14 +1,15 @@
|
||||||
"""
|
"""
|
||||||
Approximates the area under the curve using the trapezoidal rule
|
Approximates the area under the curve using the trapezoidal rule
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Callable, Union
|
from typing import Callable
|
||||||
|
|
||||||
|
|
||||||
def trapezoidal_area(
|
def trapezoidal_area(
|
||||||
fnc: Callable[[Union[int, float]], Union[int, float]],
|
fnc: Callable[[int | float], int | float],
|
||||||
x_start: Union[int, float],
|
x_start: int | float,
|
||||||
x_end: Union[int, float],
|
x_end: int | float,
|
||||||
steps: int = 100,
|
steps: int = 100,
|
||||||
) -> float:
|
) -> float:
|
||||||
|
|
||||||
|
|
|
@ -10,13 +10,12 @@ Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
|
||||||
doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
|
doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
|
||||||
Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem
|
Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import math
|
import math
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
def prime_sieve(num: int) -> List[int]:
|
def prime_sieve(num: int) -> list[int]:
|
||||||
"""
|
"""
|
||||||
Returns a list with all prime numbers up to n.
|
Returns a list with all prime numbers up to n.
|
||||||
|
|
||||||
|
|
|
@ -3,11 +3,12 @@ Find Volumes of Various Shapes.
|
||||||
|
|
||||||
Wikipedia reference: https://en.wikipedia.org/wiki/Volume
|
Wikipedia reference: https://en.wikipedia.org/wiki/Volume
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from math import pi, pow
|
from math import pi, pow
|
||||||
from typing import Union
|
|
||||||
|
|
||||||
|
|
||||||
def vol_cube(side_length: Union[int, float]) -> float:
|
def vol_cube(side_length: int | float) -> float:
|
||||||
"""
|
"""
|
||||||
Calculate the Volume of a Cube.
|
Calculate the Volume of a Cube.
|
||||||
|
|
||||||
|
|
|
@ -1,10 +1,8 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Union
|
|
||||||
|
|
||||||
|
|
||||||
def search_in_a_sorted_matrix(
|
def search_in_a_sorted_matrix(
|
||||||
mat: list[list], m: int, n: int, key: Union[int, float]
|
mat: list[list], m: int, n: int, key: int | float
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
>>> search_in_a_sorted_matrix(
|
>>> search_in_a_sorted_matrix(
|
||||||
|
|
|
@ -14,7 +14,7 @@ def date_to_weekday(inp_date: str) -> str:
|
||||||
>>> date_to_weekday("1/1/2021")
|
>>> date_to_weekday("1/1/2021")
|
||||||
'Friday'
|
'Friday'
|
||||||
"""
|
"""
|
||||||
day, month, year = [int(x) for x in inp_date.split("/")]
|
day, month, year = (int(x) for x in inp_date.split("/"))
|
||||||
if year % 100 == 0:
|
if year % 100 == 0:
|
||||||
year = "00"
|
year = "00"
|
||||||
new_base_date: str = f"{day}/{month}/{year%100} 0:0:0"
|
new_base_date: str = f"{day}/{month}/{year%100} 0:0:0"
|
||||||
|
|
|
@ -8,9 +8,9 @@ conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiabi
|
||||||
|
|
||||||
For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm
|
For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import random
|
import random
|
||||||
from typing import Dict, List
|
|
||||||
|
|
||||||
|
|
||||||
class Clause:
|
class Clause:
|
||||||
|
@ -27,7 +27,7 @@ class Clause:
|
||||||
True
|
True
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, literals: List[int]) -> None:
|
def __init__(self, literals: list[int]) -> None:
|
||||||
"""
|
"""
|
||||||
Represent the literals and an assignment in a clause."
|
Represent the literals and an assignment in a clause."
|
||||||
"""
|
"""
|
||||||
|
@ -52,7 +52,7 @@ class Clause:
|
||||||
"""
|
"""
|
||||||
return len(self.literals)
|
return len(self.literals)
|
||||||
|
|
||||||
def assign(self, model: Dict[str, bool]) -> None:
|
def assign(self, model: dict[str, bool]) -> None:
|
||||||
"""
|
"""
|
||||||
Assign values to literals of the clause as given by model.
|
Assign values to literals of the clause as given by model.
|
||||||
"""
|
"""
|
||||||
|
@ -68,7 +68,7 @@ class Clause:
|
||||||
value = not value
|
value = not value
|
||||||
self.literals[literal] = value
|
self.literals[literal] = value
|
||||||
|
|
||||||
def evaluate(self, model: Dict[str, bool]) -> bool:
|
def evaluate(self, model: dict[str, bool]) -> bool:
|
||||||
"""
|
"""
|
||||||
Evaluates the clause with the assignments in model.
|
Evaluates the clause with the assignments in model.
|
||||||
This has the following steps:
|
This has the following steps:
|
||||||
|
@ -97,7 +97,7 @@ class Formula:
|
||||||
{{A1, A2, A3'}, {A5', A2', A1}} is ((A1 v A2 v A3') and (A5' v A2' v A1))
|
{{A1, A2, A3'}, {A5', A2', A1}} is ((A1 v A2 v A3') and (A5' v A2' v A1))
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, clauses: List[Clause]) -> None:
|
def __init__(self, clauses: list[Clause]) -> None:
|
||||||
"""
|
"""
|
||||||
Represent the number of clauses and the clauses themselves.
|
Represent the number of clauses and the clauses themselves.
|
||||||
"""
|
"""
|
||||||
|
@ -146,7 +146,7 @@ def generate_formula() -> Formula:
|
||||||
return Formula(set(clauses))
|
return Formula(set(clauses))
|
||||||
|
|
||||||
|
|
||||||
def generate_parameters(formula: Formula) -> (List[Clause], List[str]):
|
def generate_parameters(formula: Formula) -> (list[Clause], list[str]):
|
||||||
"""
|
"""
|
||||||
Return the clauses and symbols from a formula.
|
Return the clauses and symbols from a formula.
|
||||||
A symbol is the uncomplemented form of a literal.
|
A symbol is the uncomplemented form of a literal.
|
||||||
|
@ -173,8 +173,8 @@ def generate_parameters(formula: Formula) -> (List[Clause], List[str]):
|
||||||
|
|
||||||
|
|
||||||
def find_pure_symbols(
|
def find_pure_symbols(
|
||||||
clauses: List[Clause], symbols: List[str], model: Dict[str, bool]
|
clauses: list[Clause], symbols: list[str], model: dict[str, bool]
|
||||||
) -> (List[str], Dict[str, bool]):
|
) -> (list[str], dict[str, bool]):
|
||||||
"""
|
"""
|
||||||
Return pure symbols and their values to satisfy clause.
|
Return pure symbols and their values to satisfy clause.
|
||||||
Pure symbols are symbols in a formula that exist only
|
Pure symbols are symbols in a formula that exist only
|
||||||
|
@ -225,8 +225,8 @@ def find_pure_symbols(
|
||||||
|
|
||||||
|
|
||||||
def find_unit_clauses(
|
def find_unit_clauses(
|
||||||
clauses: List[Clause], model: Dict[str, bool]
|
clauses: list[Clause], model: dict[str, bool]
|
||||||
) -> (List[str], Dict[str, bool]):
|
) -> (list[str], dict[str, bool]):
|
||||||
"""
|
"""
|
||||||
Returns the unit symbols and their values to satisfy clause.
|
Returns the unit symbols and their values to satisfy clause.
|
||||||
Unit symbols are symbols in a formula that are:
|
Unit symbols are symbols in a formula that are:
|
||||||
|
@ -273,8 +273,8 @@ def find_unit_clauses(
|
||||||
|
|
||||||
|
|
||||||
def dpll_algorithm(
|
def dpll_algorithm(
|
||||||
clauses: List[Clause], symbols: List[str], model: Dict[str, bool]
|
clauses: list[Clause], symbols: list[str], model: dict[str, bool]
|
||||||
) -> (bool, Dict[str, bool]):
|
) -> (bool, dict[str, bool]):
|
||||||
"""
|
"""
|
||||||
Returns the model if the formula is satisfiable, else None
|
Returns the model if the formula is satisfiable, else None
|
||||||
This has the following steps:
|
This has the following steps:
|
|
@ -1,4 +1,6 @@
|
||||||
from typing import Callable, Optional
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
|
||||||
class DoubleLinkedListNode:
|
class DoubleLinkedListNode:
|
||||||
|
@ -119,7 +121,7 @@ class LFUCache:
|
||||||
"""
|
"""
|
||||||
return key in self.cache
|
return key in self.cache
|
||||||
|
|
||||||
def get(self, key: int) -> Optional[int]:
|
def get(self, key: int) -> int | None:
|
||||||
"""
|
"""
|
||||||
Returns the value for the input key and updates the Double Linked List. Returns
|
Returns the value for the input key and updates the Double Linked List. Returns
|
||||||
None if key is not present in cache
|
None if key is not present in cache
|
||||||
|
|
|
@ -1,4 +1,6 @@
|
||||||
from typing import Callable, Optional
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
|
||||||
class DoubleLinkedListNode:
|
class DoubleLinkedListNode:
|
||||||
|
@ -125,7 +127,7 @@ class LRUCache:
|
||||||
|
|
||||||
return key in self.cache
|
return key in self.cache
|
||||||
|
|
||||||
def get(self, key: int) -> Optional[int]:
|
def get(self, key: int) -> int | None:
|
||||||
"""
|
"""
|
||||||
Returns the value for the input key and updates the Double Linked List. Returns
|
Returns the value for the input key and updates the Double Linked List. Returns
|
||||||
None if key is not present in cache
|
None if key is not present in cache
|
||||||
|
|
|
@ -26,7 +26,7 @@ def solution(n: int = 1000) -> int:
|
||||||
0
|
0
|
||||||
"""
|
"""
|
||||||
|
|
||||||
return sum([e for e in range(3, n) if e % 3 == 0 or e % 5 == 0])
|
return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -25,7 +25,7 @@ def solution(n: int = 1000) -> int:
|
||||||
83700
|
83700
|
||||||
"""
|
"""
|
||||||
|
|
||||||
return sum([i for i in range(n) if i % 3 == 0 or i % 5 == 0])
|
return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -33,7 +33,7 @@ def solution(n: int = 100) -> int:
|
||||||
1582700
|
1582700
|
||||||
"""
|
"""
|
||||||
|
|
||||||
sum_of_squares = sum([i * i for i in range(1, n + 1)])
|
sum_of_squares = sum(i * i for i in range(1, n + 1))
|
||||||
square_of_sum = int(math.pow(sum(range(1, n + 1)), 2))
|
square_of_sum = int(math.pow(sum(range(1, n + 1)), 2))
|
||||||
return square_of_sum - sum_of_squares
|
return square_of_sum - sum_of_squares
|
||||||
|
|
||||||
|
|
|
@ -70,10 +70,7 @@ def solution(n: str = N) -> int:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
return max(
|
return max(
|
||||||
[
|
reduce(lambda x, y: int(x) * int(y), n[i : i + 13]) for i in range(len(n) - 12)
|
||||||
reduce(lambda x, y: int(x) * int(y), n[i : i + 13])
|
|
||||||
for i in range(len(n) - 12)
|
|
||||||
]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -29,7 +29,7 @@ def triangle_number_generator():
|
||||||
|
|
||||||
|
|
||||||
def count_divisors(n):
|
def count_divisors(n):
|
||||||
return sum([2 for i in range(1, int(n ** 0.5) + 1) if n % i == 0 and i * i != n])
|
return sum(2 for i in range(1, int(n ** 0.5) + 1) if n % i == 0 and i * i != n)
|
||||||
|
|
||||||
|
|
||||||
def solution():
|
def solution():
|
||||||
|
|
|
@ -18,7 +18,7 @@ def solution():
|
||||||
"""
|
"""
|
||||||
file_path = os.path.join(os.path.dirname(__file__), "num.txt")
|
file_path = os.path.join(os.path.dirname(__file__), "num.txt")
|
||||||
with open(file_path) as file_hand:
|
with open(file_path) as file_hand:
|
||||||
return str(sum([int(line) for line in file_hand]))[:10]
|
return str(sum(int(line) for line in file_hand))[:10]
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -25,10 +25,10 @@ that all starting numbers finish at 1.
|
||||||
|
|
||||||
Which starting number, under one million, produces the longest chain?
|
Which starting number, under one million, produces the longest chain?
|
||||||
"""
|
"""
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def collatz_sequence(n: int) -> List[int]:
|
def collatz_sequence(n: int) -> list[int]:
|
||||||
"""Returns the Collatz sequence for n."""
|
"""Returns the Collatz sequence for n."""
|
||||||
sequence = [n]
|
sequence = [n]
|
||||||
while n != 1:
|
while n != 1:
|
||||||
|
@ -54,7 +54,7 @@ def solution(n: int = 1000000) -> int:
|
||||||
13255
|
13255
|
||||||
"""
|
"""
|
||||||
|
|
||||||
result = max([(len(collatz_sequence(i)), i) for i in range(1, n)])
|
result = max((len(collatz_sequence(i)), i) for i in range(1, n))
|
||||||
return result[1]
|
return result[1]
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -28,7 +28,7 @@ def solution(num: int = 100) -> int:
|
||||||
>>> solution(1)
|
>>> solution(1)
|
||||||
1
|
1
|
||||||
"""
|
"""
|
||||||
return sum([int(x) for x in str(factorial(num))])
|
return sum(int(x) for x in str(factorial(num)))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -41,11 +41,9 @@ def solution(n: int = 10000) -> int:
|
||||||
0
|
0
|
||||||
"""
|
"""
|
||||||
total = sum(
|
total = sum(
|
||||||
[
|
i
|
||||||
i
|
for i in range(1, n)
|
||||||
for i in range(1, n)
|
if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i
|
||||||
if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i
|
|
||||||
]
|
|
||||||
)
|
)
|
||||||
return total
|
return total
|
||||||
|
|
||||||
|
|
|
@ -14,8 +14,9 @@ and denominator.
|
||||||
If the product of these four fractions is given in its lowest common
|
If the product of these four fractions is given in its lowest common
|
||||||
terms, find the value of the denominator.
|
terms, find the value of the denominator.
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from fractions import Fraction
|
from fractions import Fraction
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
def is_digit_cancelling(num: int, den: int) -> bool:
|
def is_digit_cancelling(num: int, den: int) -> bool:
|
||||||
|
@ -26,7 +27,7 @@ def is_digit_cancelling(num: int, den: int) -> bool:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def fraction_list(digit_len: int) -> List[str]:
|
def fraction_list(digit_len: int) -> list[str]:
|
||||||
"""
|
"""
|
||||||
>>> fraction_list(2)
|
>>> fraction_list(2)
|
||||||
['16/64', '19/95', '26/65', '49/98']
|
['16/64', '19/95', '26/65', '49/98']
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user