Hey, I'm new here and new to programming. All of the questions were pretty easy to figure out but I'm having difficulty with the last questions.
It states "write a python loop to correctly compute below:
1/2 +2/3 + 3/4... 9/10
I have done a few things with loops but I am not sure how to code this with fractions and the loop.
Thank you for the help!
What have you thought about? Here are some hints: in each fraction, what is the difference between the numerator and the denominator? What about between successive fractions?
Do we want the answer as a fraction?
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
I think it's good to tell people about the existence of parts of the standard library that are useful for solving particular problems, but I don't think one should be solving the problem for them. By doing the work (or a large part of it) for them, they don't get the benefit of thinking for themselves.