Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When implementing a recursive function, you need to think about two cases: the base case and the recursive case.</p> <p>In the base case, the function doesn't call itself recursively. It may do some work in this case, or it may do nothing because all the work has already been done.</p> <p>In the recursive case, the function does a little bit of work to get itself closer to the goal, then calls itself recursively to get the rest of the work done.</p> <p>Here's a way to break down your problem for a recursive function.</p> <p>In the recursive case, the “little bit of work” is setting the sign of one number in the list to positive, and <strong>also</strong> to set the sign of that number to negative. We need to recurse after both assignments, because we need to generate combinations for each sign.</p> <p>In the base case, all of the numbers have had their signs set, so we just print the list of numbers.</p> <p>In Python, for example, we could start by setting up the function to take a list of numbers, and the index of the next number needing its sign set. To start, the next number is the first number in the list, at index 0:</p> <pre><code>def allSignCombinations(numbers, nextNumberIndex=0): </code></pre> <p>The base case happens when <code>nextNumberIndex</code> is equal to <code>len(numbers)</code>, meaning there are no numbers left needing their signs set:</p> <pre><code> if nextNumberIndex == len(numbers): print numbers </code></pre> <p>Otherwise, we do that “little bit of work”. We set the sign of the next number to both positive and negative, and we recurse for each sign. When we recurse, we tell the next call to work starting at the next number in the list, if there is one:</p> <pre><code> else: numbers[nextNumberIndex] = abs(numbers[nextNumberIndex]) allSignCombinations(numbers, nextNumberIndex + 1) numbers[nextNumberIndex] = -numbers[nextNumberIndex] allSignCombinations(numbers, nextNumberIndex + 1) </code></pre>
    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