TheAlgorithms-Python
51 строка · 1.4 Кб
1"""
2This is a pure Python implementation of the P-Series algorithm
3https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series
4For doctests run following command:
5python -m doctest -v p_series.py
6or
7python3 -m doctest -v p_series.py
8For manual testing run:
9python3 p_series.py
10"""
11
12from __future__ import annotations13
14
15def p_series(nth_term: float | str, power: float | str) -> list[str]:16"""17Pure Python implementation of P-Series algorithm
18:return: The P-Series starting from 1 to last (nth) term
19Examples:
20>>> p_series(5, 2)
21['1', '1 / 4', '1 / 9', '1 / 16', '1 / 25']
22>>> p_series(-5, 2)
23[]
24>>> p_series(5, -2)
25['1', '1 / 0.25', '1 / 0.1111111111111111', '1 / 0.0625', '1 / 0.04']
26>>> p_series("", 1000)
27['']
28>>> p_series(0, 0)
29[]
30>>> p_series(1, 1)
31['1']
32"""
33if nth_term == "":34return [""]35nth_term = int(nth_term)36power = int(power)37series: list[str] = []38for temp in range(int(nth_term)):39series.append(f"1 / {pow(temp + 1, int(power))}" if series else "1")40return series41
42
43if __name__ == "__main__":44import doctest45
46doctest.testmod()47
48nth_term = int(input("Enter the last number (nth term) of the P-Series"))49power = int(input("Enter the power for P-Series"))50print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p")51print(p_series(nth_term, power))52