0

I was wondering whether there is an agreed-upon convention about what is better for depth-first search in python - stack using list or recursion. Is there a standard for this or it is heavily dependent on a use case?

  • 1
    Recursion in python is pretty slow and inefficient compared to recursion in other languages. Thus, in python: always avoid recursion, unless you know that it won't be deep. – Stef Aug 04 '22 at 09:36
  • For instance, in the case of a search by dichotomy in a list of length N, it's usually okay to use recursion, since the number of recursive calls will be in the order of log2(N). But for most other things it is not okay. (This is just for python. Recursion in other languages is fine.) – Stef Aug 04 '22 at 11:31
  • Depends on the problem. Recursion is OK in Python when the depth is logarithmic but otherwise prefer iteration. Every day, there are posts of people trying to visit all elements in lists with recursion. They're in for an unpleasant surprise when they try any reasonably-sized list longer than 1000 elements. Also, they tend to be confused about how the code works--not a good thing. See [Recursion applied to lists vs trees in Python](https://stackoverflow.com/questions/66842109/recursion-applied-to-lists-vs-trees-in-python/66846438#66846438) – ggorlen Aug 04 '22 at 19:00
  • @Stef Thank you for the explanation and examples, I am grateful for your time and contribution. – Akira Asahi Aug 05 '22 at 06:34

0 Answers0