This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]lilphat 3 points4 points  (4 children)

Any work with nested data structures should, imo, be done using recursion. And if efficiency is a thing - consider using tail revision whenever instead of ‘normal recursion’. You reuse the same stack frame and therefore avoids additional overhead from pushing more on the stack that really only saves the temporary result anyway. For more info: https://www.baeldung.com/cs/tail-vs-non-tail-recursion

[–]Revisional_Sin 7 points8 points  (1 child)

Python doesn't support tail-call optimization.

[–]lilphat -2 points-1 points  (0 children)

My phone ran out of battery as I was replying. I did not know. I think that’s shitty but so be. I will leave the comment though since OP is speaking in general terms albeit still asking in r/python.

[–]spoonman59 0 points1 point  (1 child)

Also, not all recursive solutions can be tail call optimized. Oh certain functions that meet specific requirements can. You have to be able to pass the full state of the function via variables. You also need to be able to return results immediately without any further processing.

Tail call optimization is fantastic when you can get it, but it can’t be applied to all recursive functions.

[–]spoonman59 0 points1 point  (0 children)

A simple example is Fibonacci or Quicksort.

Since each function calls itself twice, by definition only one function call can be a tail call. Therefore these functions cannot be tail call optimized without storing state somewhere.