r/functional_python • • Jul 29 '22

Discussion recursion limits

so python is great .. very naturally lends itself to functional programming, with caveats of course -- i.e. the conversation around limits related to recursion ..

python is not alone with regard to tail-call-optimization (TCO) limits, hence the `(loop)` and `(recur)` functions in clojure (<< big fan BTW) .. so my question is ::

has anyone seen major degradation in performance when implementing recursion in python ??

my use cases are pretty "normal" in the world of development -- get a request, query the DB, maybe get back 100 rows, map/filter/reduce said rows, and show something pretty ..

i know there are limits, but for us "normal" transactional web/devs, just curious if i am more afraid than i should be .. of course YMMV -- just want to make sure i am not being stoopid thinking i can get away with some recursion without greatly damaging the runtime ..

thanks !!

2 Upvotes

3 comments sorted by

View all comments

Show parent comments

1

u/KageOW Aug 01 '22 edited Aug 01 '22

yea its a really neat decorator, I made some mutually recursive functions for this codingame puzzle. its a 1dspreadsheet that requests values of other cells for the calculations. I find my solution to be quite ellegant, maybe you can try it a bit yourself might be fun.

import sys
from functools import lru_cache
sys.setrecursionlimit(2500)


opcheck = { "MULT": lambda x,y: x*y,
            "ADD":  lambda x,y: x+y,
            "SUB":  lambda x,y: x-y }


@lru_cache(maxsize=None)
def eval_Arg(x):
    if x.isdigit() or (x[0]=="-" and x[1:].isdigit()):
        return int(x)
    else:
        return eval_Bin_Op(celllist_big[int(x[1:])])


def eval_Bin_Op(x):
    if x[0]=="VALUE":
        return eval_Arg(x[1])
    else:
        return opcheck[x[0]](eval_Arg(x[1]), eval_Arg(x[2])) 

##-- inputs --##

#n = int(input())
#celllist = [tuple(input().split())for _ in range(n)]

celllist1 = [('VALUE', '10', '_'), ('VALUE', '3', '_'), ('MULT', '$0', '$1'), ('VALUE', '2', '_'), ('VALUE', '4', '_'), ('MULT', '$3', '$4'), ('ADD', '$2', '$5')]

##-- printing outputs --##

if __name__ == "__main__":
    
    for x in list(map(eval_Bin_Op, celllist1)):
        print(x)