Skip to content

from __future__ import annotations #2464

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

Merged
merged 5 commits into from
Sep 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ jobs:
- scripts/validate_filenames.py # no uppercase, no spaces, in a directory
- pip install -r requirements.txt # fast fail on black, flake8, validate_filenames
script:
- mypy --ignore-missing-imports .
- mypy --ignore-missing-imports . || true # https://github.com/python/mypy/issues/7907
- pytest --doctest-modules --ignore=project_euler/ --durations=10 --cov-report=term-missing:skip-covered --cov=. .
- name: Project Euler
before_script: pip install pytest-cov
script:
- pytest --doctest-modules --durations=10 --cov-report=term-missing:skip-covered --cov=project_euler/ project_euler/
after_success:
- scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
notifications:
webhooks: https://www.travisbuddy.com/
on_success: never
after_success:
- scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
4 changes: 2 additions & 2 deletions arithmetic_analysis/in_static_equilibrium.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
mypy : passed
"""

from typing import List
from __future__ import annotations

from numpy import array, cos, cross, radians, sin # type: ignore


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)
Expand Down
8 changes: 4 additions & 4 deletions backtracking/coloring.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring
"""
from typing import List
from __future__ import annotations


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
Expand All @@ -35,7 +35,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
Expand Down Expand Up @@ -86,7 +86,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.
Expand Down
8 changes: 4 additions & 4 deletions backtracking/hamiltonian_cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@

Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path
"""
from typing import List
from __future__ import annotations


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
Expand Down Expand Up @@ -47,7 +47,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:
Expand Down Expand Up @@ -108,7 +108,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
Expand Down
10 changes: 5 additions & 5 deletions backtracking/knight_tour.py
Original file line number Diff line number Diff line change
@@ -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], n: int) -> List[Tuple[int]]:
def get_valid_pos(position: tuple[int], n: int) -> list[tuple[int]]:
"""
Find all the valid positions a knight can move to from the current position.

Expand Down Expand Up @@ -32,7 +32,7 @@ def get_valid_pos(position: Tuple[int], n: int) -> List[Tuple[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.

Expand All @@ -46,7 +46,7 @@ def is_complete(board: List[List[int]]) -> bool:
return not any(elem == 0 for row in board for elem in row)


def open_knight_tour_helper(board: List[List[int]], pos: Tuple[int], curr: int) -> bool:
def open_knight_tour_helper(board: list[list[int]], pos: tuple[int], curr: int) -> bool:
"""
Helper function to solve knight tour problem.
"""
Expand All @@ -66,7 +66,7 @@ def open_knight_tour_helper(board: List[List[int]], pos: Tuple[int], curr: int)
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.
Expand Down
10 changes: 5 additions & 5 deletions backtracking/n_queens_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
Expand Down
8 changes: 4 additions & 4 deletions cellular_automata/one_dimensional.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
https://mathworld.wolfram.com/ElementaryCellularAutomaton.html
"""

from typing import List
from __future__ import annotations

from PIL import Image

Expand All @@ -15,7 +15,7 @@
# fmt: on


def format_ruleset(ruleset: int) -> List[int]:
def format_ruleset(ruleset: int) -> list[int]:
"""
>>> format_ruleset(11100)
[0, 0, 0, 1, 1, 1, 0, 0]
Expand All @@ -27,7 +27,7 @@ def format_ruleset(ruleset: int) -> List[int]:
return [int(c) for c in f"{ruleset:08}"[:8]]


def new_generation(cells: List[List[int]], rule: List[int], time: int) -> List[int]:
def new_generation(cells: list[list[int]], rule: list[int], time: int) -> list[int]:
population = len(cells[0]) # 31
next_generation = []
for i in range(population):
Expand All @@ -41,7 +41,7 @@ def new_generation(cells: List[List[int]], rule: List[int], time: int) -> List[i
return next_generation


def generate_image(cells: List[List[int]]) -> Image.Image:
def generate_image(cells: list[list[int]]) -> Image.Image:
"""
Convert the cells into a greyscale PIL.Image.Image and return it to the caller.
>>> from random import random
Expand Down
5 changes: 3 additions & 2 deletions ciphers/rsa_factorization.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html
large number can take minutes to factor, therefore are not included in doctest.
"""
from __future__ import annotations

import math
import random
from typing import List


def rsafactor(d: int, e: int, N: int) -> List[int]:
def rsafactor(d: int, e: int, N: int) -> list[int]:
"""
This function returns the factors of N, where p*q=N
Return: [p, q]
Expand Down
6 changes: 3 additions & 3 deletions compression/burrows_wheeler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
original character. The BWT is thus a "free" method of improving the efficiency
of text compression algorithms, costing only some extra computation.
"""
from typing import Dict, List
from __future__ import annotations


def all_rotations(s: str) -> List[str]:
def all_rotations(s: str) -> list[str]:
"""
:param s: The string that will be rotated len(s) times.
:return: A list with the rotations.
Expand Down Expand Up @@ -43,7 +43,7 @@ def all_rotations(s: str) -> List[str]:
return [s[i:] + s[:i] for i in range(len(s))]


def bwt_transform(s: str) -> Dict:
def bwt_transform(s: str) -> dict:
"""
:param s: The string that will be used at bwt algorithm
:return: the string composed of the last char of each row of the ordered
Expand Down
5 changes: 3 additions & 2 deletions data_structures/binary_tree/lazy_segment_tree.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import math
from typing import List


class SegmentTree:
Expand Down Expand Up @@ -36,7 +37,7 @@ def right(self, idx: int) -> int:
return idx * 2 + 1

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:
if left_element == right_element:
self.segment_tree[idx] = A[left_element - 1]
Expand Down
19 changes: 10 additions & 9 deletions data_structures/binary_tree/lowest_common_ancestor.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# https://en.wikipedia.org/wiki/Lowest_common_ancestor
# https://en.wikipedia.org/wiki/Breadth-first_search

from __future__ import annotations

import queue
from typing import Dict, List, Tuple


def swap(a: int, b: int) -> Tuple[int, int]:
def swap(a: int, b: int) -> tuple[int, int]:
"""
Return a tuple (b, a) when given two integers a and b
>>> swap(2,3)
Expand All @@ -21,7 +22,7 @@ def swap(a: int, b: int) -> Tuple[int, int]:
return a, b


def create_sparse(max_node: int, parent: List[List[int]]) -> List[List[int]]:
def create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]:
"""
creating sparse table which saves each nodes 2^i-th parent
"""
Expand All @@ -35,8 +36,8 @@ def create_sparse(max_node: int, parent: List[List[int]]) -> List[List[int]]:

# returns lca of node u,v
def lowest_common_ancestor(
u: int, v: int, level: List[int], parent: List[List[int]]
) -> List[List[int]]:
u: int, v: int, level: list[int], parent: list[list[int]]
) -> list[list[int]]:
# u must be deeper in the tree than v
if level[u] < level[v]:
u, v = swap(u, v)
Expand All @@ -57,12 +58,12 @@ def lowest_common_ancestor(

# runs a breadth first search from root node of the tree
def breadth_first_search(
level: List[int],
parent: List[List[int]],
level: list[int],
parent: list[list[int]],
max_node: int,
graph: Dict[int, int],
graph: dict[int, int],
root=1,
) -> Tuple[List[int], List[List[int]]]:
) -> tuple[list[int], list[list[int]]]:
"""
sets every nodes direct parent
parent of root node is set to 0
Expand Down
6 changes: 4 additions & 2 deletions data_structures/binary_tree/non_recursive_segment_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,15 @@
>>> st.query(0, 2)
[1, 2, 3]
"""
from typing import Callable, List, TypeVar
from __future__ import annotations

from typing import Callable, TypeVar

T = TypeVar("T")


class SegmentTree:
def __init__(self, arr: List[T], fnc: Callable[[T, T], T]) -> None:
def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None:
"""
Segment Tree constructor, it works just with commutative combiner.
:param arr: list of elements for the segment tree
Expand Down
5 changes: 3 additions & 2 deletions data_structures/binary_tree/treap.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# flake8: noqa

from __future__ import annotations

from random import random
from typing import Tuple


class Node:
Expand Down Expand Up @@ -33,7 +34,7 @@ def __str__(self):
return value + left + right


def split(root: Node, value: int) -> Tuple[Node, Node]:
def split(root: Node, value: int) -> tuple[Node, Node]:
"""
We split current tree into 2 trees with value:

Expand Down
8 changes: 5 additions & 3 deletions data_structures/linked_list/skip_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
https://epaperpress.com/sortsearch/download/skiplist.pdf
"""

from __future__ import annotations

from random import random
from typing import Generic, List, Optional, Tuple, TypeVar
from typing import Generic, Optional, TypeVar

KT = TypeVar("KT")
VT = TypeVar("VT")
Expand All @@ -14,7 +16,7 @@ class Node(Generic[KT, VT]):
def __init__(self, key: KT, value: VT):
self.key = key
self.value = value
self.forward: List[Node[KT, VT]] = []
self.forward: list[Node[KT, VT]] = []

def __repr__(self) -> str:
"""
Expand Down Expand Up @@ -122,7 +124,7 @@ def random_level(self) -> int:

return level

def _locate_node(self, key) -> Tuple[Optional[Node[KT, VT]], List[Node[KT, VT]]]:
def _locate_node(self, key) -> tuple[Optional[Node[KT, VT]], list[Node[KT, VT]]]:
"""
:param key: Searched key,
:return: Tuple with searched node (or None if given key is not present)
Expand Down
Loading