I've written a small program that calculates Arithmetic and Geometric Partial Sums. I'd like feedback on anything possible, since I intend on writing a cheatsheet that encapsulates all PreCalculus equations.
partial_sum.py
"""
This is a program that calculates arithmetic and geometric
partial sums
"""
from fractions import Fraction
def find_an(parsed_series):
"""
Finds an in the passed parsed arithmetic series
:param parsed_series: The series to be analyzed
"""
for i, _ in enumerate(parsed_series):
if parsed_series[i] == ".":
return int(parsed_series[i + 1])
return None
def arithmetic_partial_sum(series):
"""
Returns the partial sum of an arithmetic series
Formula:
S = n( (a1 + an) / 2 )
Find an:
an = a1 + (n - 1)d
Find n:
n = 1 + ( (an - a1) / d )
:param series: Arithmetic series to solve
"""
series = series.split("+")
a1 = int(series[0])
d = int(series[1]) - a1
an = find_an(series)
n = 1 + ((an - a1) / d)
S = n * ((a1 + an) / 2)
return S
def geometric_partial_sum(series):
"""
Returns the partial sum of the geometric series
:param series: Geometric series to solve
Formula:
S = (a1 * (1 - (r ** n))) / (1 - r)
"""
series = series.split("+")
a1 = int(series[0])
r = int(series[1]) / a1
n = len(series)
S = (a1 * (1 - (r ** n))) / (1 - r)
return str(Fraction(S).limit_denominator())
if __name__ == '__main__':
A_SERIES = "3+7+11+15+.+99"
G_SERIES = f"3+1+{1/3}+{1/9}+{1/27}+{1/81}"
print(arithmetic_partial_sum(A_SERIES))
print(geometric_partial_sum(G_SERIES))