Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes, there are plenty of times I would not use recursion. Recursion is <em>not</em> free, it has a cost in stack space and that can often be a much more limited resource than some others. There's also a time cost, however small, in setting up and tearing down stack frames.</p> <p>By way of example, the much vaunted factorial function is one where I would probably opt for an iterative approach where the numbers were large. Calculating 10000! with:</p> <pre><code>def factorial (n): if n = 1 return 1 return n * factorial (n-1) </code></pre> <p>will use 10,000 stack frames (assuming it's not optimised by the compiler into an iterative solution of course), quite a lot. The iterative solution:</p> <pre><code>def factorial (n) r = 1 while n &gt; 1: r = r * n n = n - 1 return r </code></pre> <p>will use just the one stack frame and precious little else.</p> <p>It's true that recursive solutions are often more elegant code but you have to temper that with the limitations of your environment.</p> <p>Your <code>carbon</code> example is one where I would actually use recursion since:</p> <ul> <li>it uses at most six stack frames (one per character in the string); and</li> <li>it's relatively elegant, at least much more so than six nested loops and huge equality checks.</li> </ul> <p>For example the following Python code does the trick:</p> <pre><code>def recur (str, pref = ""): # Terminating condition. if str == "": print pref return # Rotate string so all letters get a chance to be first. for i in range (len (str)): recur (str[1:], pref + str[:1]) str = str[1:] + str[:1] recur ("abc") </code></pre> <p>producing:</p> <pre><code>abc acb bca bac cab cba </code></pre> <p>Of course, if your string can be 10K long, I'd rethink it, since that would involve a lot more stack levels but, provided you keep in low enough, recursion is a viable solution.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload