A half solution based on Fraction with a different algorithm.
Why not a complete solution? Maybe you want to access single elements in the list, before you sum all up.
If you apply
sum()
on a list with
Fraction
s, you'll get a sum as
Fraction
.
Very handy because there is no lost in accuracy.
Only if you convert it to an
int
or
float
, you lose accuracy.
from fractions import Fraction
def gen(n):
"""
Return as list of Frcations by following pattern:
1/2, 2/3, 3/4, ...
"""
# a list to append the fractions
results = []
# we need a start point for numerator and denominator
numerator, denominator = 1, 2
for _ in range(n):
# this loop does the work
results.append(Fraction(numerator, denominator))
# here are the count-up of numerator and denominator assigned
numerator, denominator = denominator, denominator + 1
return results
If the fractions are not required, and you want just want to sum them up, the solution is easier than this provided example.
Instead of appending, you can use the
+=
operator for inline addition.
result = Fraction(0)
# in the for-loop
result += Fraction(numerator, denominator)
# then numerator and denominator must be changed
# then the next iteration, which uses the last numerator and denominator
After 10 edits I may get this right :-D