How can I rewrite this loop using lambda and list-comprehension?
n = 17
e = 0
for i in range(0, n):
e = 1 / factorial(i)
print(e)
So far I have tried this...but it's not working
lst = [item for item in map(lambda e: e 1/factorial(i), range(0,n))])
myMap = map(lambda e: e 1/factorial(i), range(0,n))
CodePudding user response:
I would use the sum function for this. I also don't understand why you are using the map function together with a list comprehension.
e = sum([1 / factorial(i) for i in range(n)])
As you can see, list comprehensions can also be used to modify the returned list. You don't need to do complex and not working things using map and lambda.
To be complete, the map function returns the sum of all values in a list. For example:
>>> l = [1, 2, 3, 4, 5, 6]
>>>
>>> sum(l)
21
CodePudding user response:
Since list comprehension and lambda does not fit well in this case, here some functional programming base approaches to, hope, make clear the difference:
A reduce
approach: a list is contracted to a "number" via a functional
from math import factorial
from functools import reduce
n = 10
reduce(lambda i, j: i 1/factorial(j), range(n), 0)
#2.7182815255731922
here with map
: consecutive 1-to-1 correspondences in which a function is applied termwise. Finally a functional to contract the list into a "number"
sum(map(int(-1).__rpow__, map(factorial, range(n))))
#2.7182815255731922