Skip to content

[mypy] Fix type annotations for maths directory #5782

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 45 commits into from
Nov 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
e34dd4d
[mypy] Fix annotations in `maths/series/p_series.py`
Rohanrbharadwaj Nov 6, 2021
cea397e
Update p_series.py
Rohanrbharadwaj Nov 6, 2021
7173166
Update p_series.py
Rohanrbharadwaj Nov 6, 2021
b5440ec
Remove from excluded in mypy.ini
Rohanrbharadwaj Nov 6, 2021
1ce55e7
Type annotation for series
Rohanrbharadwaj Nov 6, 2021
95e41dd
Annotate maths/proth_number.py (properly)
Rohanrbharadwaj Nov 6, 2021
4f00c09
Remove from excluded in mypy.ini
Rohanrbharadwaj Nov 6, 2021
99a0cf5
Annotate average_mode.py
Rohanrbharadwaj Nov 6, 2021
e9c81ab
Update average_mode.py
Rohanrbharadwaj Nov 6, 2021
d2a04cf
Update average_mode.py
Rohanrbharadwaj Nov 6, 2021
567210b
Update average_mode.py
Rohanrbharadwaj Nov 6, 2021
6b07a1f
Update average_mode.py
Rohanrbharadwaj Nov 6, 2021
175b785
Remove from excluded in mypy.ini
Rohanrbharadwaj Nov 6, 2021
9902c88
Fix annotations in gamma_recursive.py
Rohanrbharadwaj Nov 6, 2021
e52a293
Remove from excluded in mypy.ini
Rohanrbharadwaj Nov 6, 2021
e98c58e
Annotations for geometric_series.py
Rohanrbharadwaj Nov 6, 2021
83af001
Update geometric_series.py
Rohanrbharadwaj Nov 6, 2021
dc86c78
Update mypy.ini
Rohanrbharadwaj Nov 6, 2021
33b0977
Update average_mode.py
Rohanrbharadwaj Nov 7, 2021
9bbace1
Update average_mode.py
Rohanrbharadwaj Nov 7, 2021
bbfcc6e
Update average_mode.py
Rohanrbharadwaj Nov 7, 2021
dbc81e9
Update mypy.ini
Rohanrbharadwaj Nov 7, 2021
289c029
Update mypy.ini
Rohanrbharadwaj Nov 7, 2021
9f7c657
Update mypy.ini
Rohanrbharadwaj Nov 7, 2021
d384199
Update average_mode.py
Rohanrbharadwaj Nov 7, 2021
db95b64
Update proth_number.py
Rohanrbharadwaj Nov 7, 2021
ae56fe9
Update average_mode.py
Rohanrbharadwaj Nov 7, 2021
b610e7f
Update gamma_recursive.py
Rohanrbharadwaj Nov 7, 2021
882a12c
Update proth_number.py
Rohanrbharadwaj Nov 7, 2021
d645da0
Merge branch 'master' into patch-3
cclauss Nov 7, 2021
d112ce4
Update mypy.ini
cclauss Nov 7, 2021
dd1ff0a
Update geometric_series.py
Rohanrbharadwaj Nov 7, 2021
c416d74
Update average_mode.py
Rohanrbharadwaj Nov 7, 2021
a9d9c1e
Update proth_number.py
Rohanrbharadwaj Nov 7, 2021
85b0ba8
Update geometric_series.py
Rohanrbharadwaj Nov 7, 2021
5078821
Update geometric_series.py
Rohanrbharadwaj Nov 7, 2021
6bf7b4c
Update geometric_series.py
Rohanrbharadwaj Nov 7, 2021
8da52be
Update p_series.py
Rohanrbharadwaj Nov 7, 2021
db01780
Update geometric_series.py
Rohanrbharadwaj Nov 7, 2021
2e5cafb
Update p_series.py
Rohanrbharadwaj Nov 7, 2021
7508c25
Update p_series.py
Rohanrbharadwaj Nov 7, 2021
e8cb833
Update geometric_series.py
Rohanrbharadwaj Nov 7, 2021
bdb576d
Update p_series.py
Rohanrbharadwaj Nov 7, 2021
a362ea5
Update p_series.py
Rohanrbharadwaj Nov 7, 2021
f4597b5
Remove data_structures/stacks/next_greater_element.py|
cclauss Nov 7, 2021
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
31 changes: 13 additions & 18 deletions maths/average_mode.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,29 @@
def mode(input_list: list) -> list: # Defining function "mode."
from typing import Any


def mode(input_list: list) -> list[Any]:
"""This function returns the mode(Mode as in the measures of
central tendency) of the input data.

The input list may contain any Datastructure or any Datatype.

>>> input_list = [2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2]
>>> mode(input_list)
>>> mode([2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2])
[2]
>>> input_list = [3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 2, 2, 2]
>>> mode(input_list)
>>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 2, 2, 2])
[2]
>>> input_list = [3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 4, 2, 2, 4, 2]
>>> mode(input_list)
>>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 4, 2, 2, 4, 2])
[2, 4]
>>> input_list = ["x", "y", "y", "z"]
>>> mode(input_list)
>>> mode(["x", "y", "y", "z"])
['y']
>>> input_list = ["x", "x" , "y", "y", "z"]
>>> mode(input_list)
>>> mode(["x", "x" , "y", "y", "z"])
['x', 'y']
"""
result = list() # Empty list to store the counts of elements in input_list
for x in input_list:
result.append(input_list.count(x))
if not result:
if not input_list:
return []
y = max(result) # Gets the maximum value in the result list.
result = [input_list.count(value) for value in input_list]
y = max(result) # Gets the maximum count in the input list.
# Gets values of modes
result = {input_list[i] for i, value in enumerate(result) if value == y}
return sorted(result)
return sorted({input_list[i] for i, value in enumerate(result) if value == y})


if __name__ == "__main__":
Expand Down
3 changes: 1 addition & 2 deletions maths/gamma_recursive.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
Gamma function is a very useful tool in math and physics.
It helps calculating complex integral in a convenient way.
for more info: https://en.wikipedia.org/wiki/Gamma_function

Python's Standard Library math.gamma() function overflows around gamma(171.624).
"""
from math import pi, sqrt
Expand Down Expand Up @@ -71,7 +70,7 @@ def test_gamma() -> None:
from doctest import testmod

testmod()
num = 1
num = 1.0
while num:
num = float(input("Gamma of: "))
print(f"gamma({num}) = {gamma(num)}")
Expand Down
14 changes: 5 additions & 9 deletions maths/proth_number.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""
Calculate the nth Proth number

Source:
https://handwiki.org/wiki/Proth_number
"""
Expand All @@ -12,22 +11,17 @@ def proth(number: int) -> int:
"""
:param number: nth number to calculate in the sequence
:return: the nth number in Proth number

Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3

>>> proth(6)
25

>>> proth(0)
Traceback (most recent call last):
...
ValueError: Input value of [number=0] must be > 0

>>> proth(-1)
Traceback (most recent call last):
...
ValueError: Input value of [number=-1] must be > 0

>>> proth(6.0)
Traceback (most recent call last):
...
Expand All @@ -44,14 +38,12 @@ def proth(number: int) -> int:
elif number == 2:
return 5
else:
block_index = number // 3
"""
+1 for binary starting at 0 i.e. 2^0, 2^1, etc.
+1 to start the sequence at the 3rd Proth number
Hence, we have a +2 in the below statement
"""
block_index = math.log(block_index, 2) + 2
block_index = int(block_index)
block_index = int(math.log(number // 3, 2)) + 2

proth_list = [3, 5]
proth_index = 2
Expand All @@ -66,6 +58,10 @@ def proth(number: int) -> int:


if __name__ == "__main__":
import doctest

doctest.testmod()

for number in range(11):
value = 0
try:
Expand Down
44 changes: 28 additions & 16 deletions maths/series/geometric_series.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""
This is a pure Python implementation of the Geometric Series algorithm
https://en.wikipedia.org/wiki/Geometric_series

Run the doctests with the following command:
python3 -m doctest -v geometric_series.py
or
Expand All @@ -11,24 +10,33 @@
"""


def geometric_series(nth_term: int, start_term_a: int, common_ratio_r: int) -> list:
"""Pure Python implementation of Geometric Series algorithm
from __future__ import annotations


def geometric_series(
nth_term: float | int,
start_term_a: float | int,
common_ratio_r: float | int,
) -> list[float | int]:
"""
Pure Python implementation of Geometric Series algorithm

:param nth_term: The last term (nth term of Geometric Series)
:param start_term_a : The first term of Geometric Series
:param common_ratio_r : The common ratio between all the terms
:return: The Geometric Series starting from first term a and multiple of common
ration with first term with increase in power till last term (nth term)
Examples:
>>> geometric_series(4, 2, 2)
[2, '4.0', '8.0', '16.0']
[2, 4.0, 8.0, 16.0]
>>> geometric_series(4.0, 2.0, 2.0)
[2.0, '4.0', '8.0', '16.0']
[2.0, 4.0, 8.0, 16.0]
>>> geometric_series(4.1, 2.1, 2.1)
[2.1, '4.41', '9.261000000000001', '19.448100000000004']
[2.1, 4.41, 9.261000000000001, 19.448100000000004]
>>> geometric_series(4, 2, -2)
[2, '-4.0', '8.0', '-16.0']
[2, -4.0, 8.0, -16.0]
>>> geometric_series(4, -2, 2)
[-2, '-4.0', '-8.0', '-16.0']
[-2, -4.0, -8.0, -16.0]
>>> geometric_series(-4, 2, 2)
[]
>>> geometric_series(0, 100, 500)
Expand All @@ -38,26 +46,30 @@ def geometric_series(nth_term: int, start_term_a: int, common_ratio_r: int) -> l
>>> geometric_series(0, 0, 0)
[]
"""
if "" in (nth_term, start_term_a, common_ratio_r):
return ""
series = []
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[float | int] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
if series == []:
series.append(start_term_a)
else:
power += 1
series.append(str(float(start_term_a) * float(multiple)))
series.append(float(start_term_a * multiple))
multiple = pow(float(common_ratio_r), power)
return series


if __name__ == "__main__":
nth_term = input("Enter the last number (n term) of the Geometric Series")
start_term_a = input("Enter the starting term (a) of the Geometric Series")
common_ratio_r = input(
"Enter the common ratio between two terms (r) of the Geometric Series"
import doctest

doctest.testmod()

nth_term = float(input("Enter the last number (n term) of the Geometric Series"))
start_term_a = float(input("Enter the starting term (a) of the Geometric Series"))
common_ratio_r = float(
input("Enter the common ratio between two terms (r) of the Geometric Series")
)
print("Formula of Geometric Series => a + ar + ar^2 ... +ar^n")
print(geometric_series(nth_term, start_term_a, common_ratio_r))
32 changes: 18 additions & 14 deletions maths/series/p_series.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,52 @@
"""
This is a pure Python implementation of the P-Series algorithm
https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series

For doctests run following command:
python -m doctest -v p_series.py
or
python3 -m doctest -v p_series.py

For manual testing run:
python3 p_series.py
"""


def p_series(nth_term: int, power: int) -> list:
"""Pure Python implementation of P-Series algorithm
from __future__ import annotations

:return: The P-Series starting from 1 to last (nth) term

def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]:
"""
Pure Python implementation of P-Series algorithm
:return: The P-Series starting from 1 to last (nth) term
Examples:
>>> p_series(5, 2)
[1, '1/4', '1/9', '1/16', '1/25']
['1', '1 / 4', '1 / 9', '1 / 16', '1 / 25']
>>> p_series(-5, 2)
[]
>>> p_series(5, -2)
[1, '1/0.25', '1/0.1111111111111111', '1/0.0625', '1/0.04']
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like a cooler test.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make all strings here instead of floats, then?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current implementation is tolerant of both. We should not lose that flexibility. Our type hint says that we expect float but our implementation is flexible to do the right thing if someone hands us something that is not a float but is still reasonable.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://pydantic-docs.helpmanual.io does a nice job of this.

['1', '1 / 0.25', '1 / 0.1111111111111111', '1 / 0.0625', '1 / 0.04']
>>> p_series("", 1000)
''
['']
>>> p_series(0, 0)
[]
>>> p_series(1, 1)
[1]
['1']
"""
if nth_term == "":
return nth_term
return [""]
nth_term = int(nth_term)
power = int(power)
series = []
series: list[str] = []
for temp in range(int(nth_term)):
series.append(f"1/{pow(temp + 1, int(power))}" if series else 1)
series.append(f"1 / {pow(temp + 1, int(power))}" if series else "1")
return series


if __name__ == "__main__":
nth_term = input("Enter the last number (nth term) of the P-Series")
power = input("Enter the power for P-Series")
import doctest

doctest.testmod()

nth_term = int(input("Enter the last number (nth term) of the P-Series"))
power = int(input("Enter the power for P-Series"))
print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p")
print(p_series(nth_term, power))
3 changes: 1 addition & 2 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@
ignore_missing_imports = True
install_types = True
non_interactive = True
exclude = (data_structures/stacks/next_greater_element.py|graphs/boruvka.py|graphs/breadth_first_search.py|graphs/breadth_first_search_2.py|graphs/check_cycle.py|graphs/finding_bridges.py|graphs/greedy_min_vertex_cover.py|graphs/random_graph_generator.py|maths/average_mode.py|maths/gamma_recursive.py|maths/proth_number.py|maths/series/geometric_series.py|maths/series/p_series.py|matrix_operation.py|other/least_recently_used.py|other/lfu_cache.py|other/lru_cache.py|searches/simulated_annealing.py|searches/ternary_search.py)

exclude = (graphs/boruvka.py|graphs/breadth_first_search.py|graphs/breadth_first_search_2.py|graphs/check_cycle.py|graphs/finding_bridges.py|graphs/greedy_min_vertex_cover.py|graphs/random_graph_generator.py|matrix_operation.py|other/least_recently_used.py|other/lfu_cache.py|other/lru_cache.py|searches/simulated_annealing.py|searches/ternary_search.py)