The Wayback Machine - https://web.archive.org/web/20211029141725/https://github.com/TheAlgorithms/Python/pull/4718/files
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pyupgrade to Python 3.9 #4718

Merged
merged 2 commits into from Sep 7, 2021
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -545,7 +545,7 @@
## Other
* [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)
* [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)
* [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)
@@ -860,6 +860,7 @@
* [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)
* [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)
* [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)
@@ -1,14 +1,14 @@
"""
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


def polar_force(
magnitude: float, angle: float, radian_mode: bool = False
) -> List[float]:
) -> list[float]:
"""
Resolves force along rectangular components.
(force, angle) => (force_x, force_y)
@@ -3,12 +3,12 @@
Reference:
- https://en.wikipedia.org/wiki/LU_decomposition
"""
from typing import Tuple
from __future__ import annotations

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
Example:
@@ -1,7 +1,7 @@
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/
from __future__ import annotations

import math
from typing import List


# for calculating u value
@@ -22,7 +22,7 @@ def ucal(u: float, p: int) -> float:

def main() -> None:
n = int(input("enter the numbers of values: "))
y: List[List[float]] = []
y: list[list[float]] = []
for i in range(n):
y.append([])
for i in range(n):
@@ -2,15 +2,16 @@
# Author: Syed Haseeb Shah (github.com/QuantumNovice)
# 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
from __future__ import annotations

from decimal import Decimal
from math import * # noqa: F401, F403
from typing import Union

from sympy import diff


def newton_raphson(
func: str, a: Union[float, Decimal], precision: float = 10 ** -10
func: str, a: float | Decimal, precision: float = 10 ** -10
) -> float:
"""Finds root from the point 'a' onwards by Newton-Raphson method
>>> newton_raphson("sin(x)", 2)
@@ -3,16 +3,16 @@
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)!)))
"""
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)
[[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)
return result

@@ -21,8 +21,8 @@ def create_all_state(
increment: int,
total_number: int,
level: int,
current_list: List[int],
total_list: List[List[int]],
current_list: list[int],
total_list: list[list[int]],
) -> None:
if level == 0:
total_list.append(current_list[:])
@@ -34,7 +34,7 @@ def create_all_state(
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:
print(*i)

@@ -5,18 +5,18 @@
Time complexity: O(n! * n),
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))])


def create_state_space_tree(
sequence: List[Union[int, str]],
current_sequence: List[Union[int, str]],
sequence: list[int | str],
current_sequence: list[int | str],
index: int,
index_used: List[int],
index_used: list[int],
) -> None:
"""
Creates a state space tree to iterate through each branch using DFS.
@@ -44,8 +44,8 @@ def create_state_space_tree(
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)

sequence_2: List[Union[int, str]] = ["A", "B", "C"]
sequence_2: list[int | str] = ["A", "B", "C"]
generate_all_permutations(sequence_2)
@@ -5,15 +5,17 @@
Time complexity: O(2^n),
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)


def create_state_space_tree(
sequence: List[Any], current_subsequence: List[Any], index: int
sequence: list[Any], current_subsequence: list[Any], index: int
) -> None:
"""
Creates a state space tree to iterate through each branch using DFS.
@@ -32,7 +34,7 @@ def create_state_space_tree(


if __name__ == "__main__":
seq: List[Any] = [3, 1, 2, 4]
seq: list[Any] = [3, 1, 2, 4]
generate_all_subsequences(seq)

seq.clear()
@@ -5,11 +5,10 @@
Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring
"""
from typing import List


def valid_coloring(
neighbours: List[int], colored_vertices: List[int], color: int
neighbours: list[int], colored_vertices: list[int], color: int
) -> bool:
"""
For each neighbour check if coloring constraint is satisfied
@@ -35,7 +34,7 @@ def valid_coloring(


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:
"""
Pseudo-Code
@@ -86,7 +85,7 @@ def util_color(
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
which will either return True or False.
@@ -6,11 +6,10 @@
Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path
"""
from typing import List


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:
"""
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)


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
Base Case:
@@ -108,7 +107,7 @@ def util_hamilton_cycle(graph: List[List[int]], path: List[int], curr_ind: int)
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"""
Wrapper function to call subroutine called util_hamilton_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

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.
@@ -32,7 +32,7 @@ def get_valid_pos(position: Tuple[int, int], n: int) -> List[Tuple[int, int]]:
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.
@@ -47,7 +47,7 @@ def is_complete(board: List[List[int]]) -> bool:


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:
"""
Helper function to solve knight tour problem.
@@ -68,7 +68,7 @@ def open_knight_tour_helper(
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
ValueError if the tour cannot be performed for the given size.
@@ -7,12 +7,13 @@
leaves of game tree is stored in scores[]
height is maximum height of Game tree
"""
from __future__ import annotations

import math
from typing import List


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:
"""
>>> import math
@@ -7,12 +7,12 @@
diagonal lines.
"""
from typing import List
from __future__ import annotations

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
considering the current state of the board.
@@ -40,7 +40,7 @@ def isSafe(board: List[List[int]], row: int, column: int) -> bool:
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
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


def printboard(board: List[List[int]]) -> None:
def printboard(board: list[list[int]]) -> None:
"""
Prints the boards that have a successful combination.
"""
@@ -75,14 +75,14 @@
for another one or vice versa.
"""
from typing import List
from __future__ import annotations


def depth_first_search(
possible_board: List[int],
diagonal_right_collisions: List[int],
diagonal_left_collisions: List[int],
boards: List[List[str]],
possible_board: list[int],
diagonal_right_collisions: list[int],
diagonal_left_collisions: list[int],
boards: list[list[str]],
n: int,
) -> None:
"""
@@ -139,7 +139,7 @@ def depth_first_search(


def n_queens_solution(n: int) -> None:
boards: List[List[str]] = []
boards: list[list[str]] = []
depth_first_search([], [], [], boards, n)

# 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.
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


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:
up, down, left, right.