How to deal with stack overflow error [Answered]
So when doing some programming competitions, i often get stack overflow, when doing recursion and the only way (i know about) to not get stack overflow is to not do deep recursion, but i was wondering, if there is any other way, as i kinda need recursion this time.
23 Replies
Your recursion must be very deep for it to give stack overflows
yea well programming competitions \ ("/) /
umm if i create a property with getter, i guess that won't work?
update it didnt work
a getter is a method, so yeah
yea i thought so, i just tried it, it was easy to change
properties ideally shouldn't have weird logic in getters and setters
use a stack
Any recursive function can be rewritten as an iterative one. Sometimes the transformation is easy; sometimes it's less so. See this, and the follow-up part 2: https://ericlippert.com/2018/12/03/removing-a-recursion-in-python/
ericlippert
Fabulous adventures in coding
Removing a recursion in Python, part 1
For the last two decades or so I’ve admired the simplicity and power of the Python language without ever actually doing any work in it or learning about the details. I’ve been taking a …
1d dp is easier with recursion + memoization, multidimensional dp is easier with tabulation
it's unlikely you get stackoverflow errors if you haven't made a mistake in your recursive function
make sure you don't recurse too much
Rwussiya#5821
REPL Result: Success
Compile: 539.326ms | Execution: 48.332ms | React with ❌ to remove this embed.
well that sucks
anyways, take the above function, change no approach whatsoever but use a stack instead and you get
Rwussiya#5821
REPL Result: Success
Compile: 667.936ms | Execution: 66.606ms | React with ❌ to remove this embed.
you are emulating the stack frame with Stack<(int, int)>, which is a heap alloc object
so it'll be way more than 1 or 4mb of stack
or change the approach and you get
Rwussiya#5821
REPL Result: Success
Compile: 566.872ms | Execution: 59.246ms | React with ❌ to remove this embed.
obviously doesnt work because overflow
i thought about using stack datastructure, my problem is that this is not normal recursion, i am calling the same method, but in different class instance, and i don't think i can implement this using stack?
can we see the problem?
sure:
basically i have some potions that must wait until some other are finished (as i said already, its coding comepetition, i don't want any hints on what i am doing wrong, what is not as optimized as it could etc. i want to figure that out on my own)
this seems like... a dp problem more than anything
without further info, you seem to be bruteforcing it
if you insist, the first step would be to turn this into a static function
i kinda can't as i am working with instance specific data
but i will try it using stack, thanks for helping
here:
then next would be to create a Stack<(int, Potion)>
and reimplement there
oh like this ok, well thanks
✅ This post has been marked as answered!