I am currently struggling on a way to compute a sum that changes its sign from addition to subtraction e.g. 1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13. I am adivised to use a forloop statement to compute this sum. Could somebody please help me out and explain the lines of code. Thanks!
You present this in a way that only needs a print statement in front of it. One line of code.
If a loop is required the data will be presented differently. Show us that and what you have tried,
than we can help.
Paul
sign = 1
total = 0
for x in range(1, 1002, 2):
total += sign/x
sign = -sign
print(total)
Not much to explain.
Example with
operator
,
iterator.cycle
and
Fraction
.
It's not the "better" way, just a different way to show up, what is Python able to do.
The better way is often lesser code and not more code.
import operator
from itertools import cycle
# Bonus: you can get the exact fraction instead of a float
from fractions import Fraction
def sum_fractions(iterations, fractions=False):
# we start with total 1
# if iterations == 0, then the int 1 is returned
# if iterations > 0, then total will convert into a float
# if fractions == True, then Fraction is used
total = 1
numerator = 1
denominator = 3
# isub and iadd replaces -= and +=
# cycle cycle through this two operator functions
op_cycle = cycle((operator.isub, operator.iadd))
# we don't need the value from range
# so assign it to the throw away name _
for _ in range(iterations):
# get the next operator function from op_cycle
op_func = next(op_cycle)
# Bonus, use Fraction to do the calculation
# Keep in mind, that this is much slower, but
# gives you exact results
if fractions:
current_value = Fraction(numerator, denominator)
else:
# without Fraction
current_value = numerator / denominator
# here the isub or iadd function is used
# instead of -= or += use here assignment
total = op_func(total, current_value)
# increment the denominator by 2
denominator += 2
return total
The benefit is, that you can do more than
+
and
-
operation.
You can extend the tuple of
op_cycle
to multiply, divide or do the modulo operation.