From Mathematica I am used to summing over a map over a list with a very short and concise syntax. E.g. to sum a map over a polynomial function:
myList = {1,2,3};
output = Sum[ x^3 x^2 x , { x, myList } ]
To do the same thing in Python, I came up with the following syntax:
myList = [1,2,3]
output = sum(list(map(lambda x: x*x*x x*x x , myList)))
My question is: Is that the most simple/efficient way of doing this? I mean, it seems to me that there should be a simpler way than nesting three or four built in functions for such a simple task.
CodePudding user response:
You don't need the map
or list
, you can just sum
using a generator expression
>>> myList = [1,2,3]
>>> sum(x**3 x**2 x for x in myList)
56
CodePudding user response:
You don't need list
. Just:
myList = [1,2,3]
output = sum(map(lambda x: x**3 x**2 x , myList))
Also, the power expression is double asterisk **
CodePudding user response:
I agree that python syntax for functional programming is not the best. Here is the way I would do it using list comprehensions:
myList = [1, 2, 3]
result_of_map = [x**3 x**2 x for x in myList]
output = sum(result_of_map)
CodePudding user response:
In Python, there is a built-in function called sum that can be used to sum a list of numbers. You can use this function to sum the results of a map operation, as you have done in your example.
However, there are a few other options that you might consider. One option is to use a list comprehension to create a new list, and then use the sum function to sum the elements of the new list:
myList = [1, 2, 3]
output = sum([x**3 x**2 x for x in myList])
Another option is to use the reduce function from the functools module to perform the sum:
from functools import reduce
myList = [1, 2, 3]
output = reduce(lambda a, b: a b, [x**3 x**2 x for x in myList])
Both of these approaches are somewhat shorter and simpler than the version using map and lambda, and they may also be more efficient in some cases. However, the difference in simplicity and efficiency may not be significant for small lists like the one in your example. Ultimately, the best approach will depend on your specific requirements and how readable you want your code to be.