Implement sum in Python

Try to implement the summation formula

\sum_{i=m}^{n} f(x) = f(m) + f(m+1) + \cdots + f(n) \\

sigma.py


def sigma(m, n, func, s = 0) :
    if m > n: return s
    return sigma(m + 1, n, func, s + func(m))

Example of use

sigma_test.py


print(sigma(1, 10, lambda x : x))
55

print(sigma(1, 3, lambda x : 3 * 5 ** (x - 1)))
93

I found a suitable problem on the Web and entered it, but it seems to work properly. There may be a more efficient writing style, a more fashionable writing style, or something that has already been prepared.

Postscript

Since there is a mathematical function library called NumPy, most of the formulas seem to be complete. .. ..

Introduction to Python Numerical Library NumPy http://rest-term.com/archives/2999/

Recommended Posts

Implement sum in Python
Implement Enigma in python
Implement XENO in python
Implement Traceroute in Python 3
Implement naive bayes in Python 3.3
Implement Redis Mutex in Python
Implement extension field in Python
Implement fast RPC in Python
Implement method chain in Python
Implement Dijkstra's Algorithm in python
Implement Slack chatbot in Python
Implement stacking learning in Python [Kaggle]
Implement R's power.prop.test function in python
Implement the Singleton pattern in Python
Quickly implement REST API in Python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
I tried to implement PLSA in Python
Implement __eq__ etc. generically in Python class
I tried to implement permutation in Python
Implement FIR filters in Python and C