Click here to Skip to main content
15,887,935 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
say I have a function f(x) were x is n^2. and say I wanted to sum the result of n^ for range of 1 - 10.

Does python have anything similar to mathmatica that would allow me pass a math function and sum the results or am I limited to a for loop

What I have tried:

so something like

Python
for n in range(1, 10):
    result += (n**2)
Posted
Updated 7-Nov-19 8:25am

Try this, where the sum() function accepts a list.
Python
result = sum([x**2 for x in range(1,11)])
 
Share this answer
 
Comments
CPallini 7-Nov-19 14:26pm    
5.You've been faster.
Nightpoison 12-Nov-19 7:52am    
Hi, Thanks for the quick post. I appreciate Question,isn't this more or less the same thing as my for loop. I"m not 100% on python and what occurs in the background. but with the exception of calling the sum function, this still contains a for loop. Is it anymore efficient?
Richard MacCutchan 12-Nov-19 11:19am    
Whether it is explicit or implicit, you cannot sum a set of numbers without a repeated for loop.
Nightpoison 19-Nov-19 8:40am    
Richard, thank you for that clarification. That makes sense to me.
Yes.
Python
result = functools.reduce(lambda a,b: a + b*b, range(1,11))

See, for instance: Functional Programming HOWTO — Python 3.8.0 documentation[^].
 
Share this answer
 
Comments
Richard MacCutchan 7-Nov-19 14:29pm    
I cheated and used Google. :)
CPallini 7-Nov-19 16:56pm    
Great minds think alike :-) I am not a Python coder,
Nightpoison 12-Nov-19 8:12am    
from my understand lamdas are that efficient of a tool. While I never mentioned efficiency as a prereq, I should have. But you did answer my question.

I personally haven't spent much time looking at lambda functions.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900