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.