What you want is this:
print(sum(decimal.Decimal(1) / i for i in range(1, 31)))
The reason your code doesn't work, is that you try to iterate over one Decimal
instance (through the use of sum
). Furthermore, your definition of var
is invalid. Your intention was probably something like this:
var = lambda i: decimal.Decimal(str(1.0 / i))
(Note the use of str
, Decimal
does not permit a floating point argument). But even then your loop would not work, because the use of sum
inside the loop is inherently flawed. sum
should be used after the loop has created all fractions that you want to sum. So that would be either of:
print(sum(var(i) for i in range(1,31)))
print(sum(map(var, range(1, 31))))
For completeness, yet another way to do this is the following:
one = decimal.Decimal(1)
unitFractions = (one / i for i in itertools.count(1))
print(sum(itertools.islice(unitFractions, 30)))
However, as mentioned by gs, the fractions provides an alternative method that yields a fractional answer:
>>> unitFractions = (fractions.Fraction(1, i) for i in itertools.count(1))
>>> print(sum(itertools.islice(unitFractions, 30)))
9304682830147/2329089562800