One way to break out of a recursive function in Python is to throw an exception and catch that at the top level. Some people will say that this is not the right way to think about recursion, but it gets the job done. Furthermore, if the task is to identify "problem" elements in an array/array of arrays/ndarray etc., a break technique is convenient, because it stops the algorithm from continuing after the global solution has been identified.

def solve_problem(lst):
    def solve_rec(l):
        '''has impl. that may throw an exception '''
    try:
        solve_rec(lst)
        return True
    except:
        return False
Answer from garde on Stack Overflow
🌐
Quora
quora.com › Is-there-any-code-to-break-out-from-recursive-functions
Is there any code to break out from recursive functions? - Quora
Answer (1 of 6): Normally to break out of a recursive function, you just conditionally exit the function and don’t recurse. For example: [code]int factorial(int x) { if (x
Discussions

How to Stop Recursion Function?
Sure, in this article, I will explain to you what recursion is and everything you need to know about recursion. As a software engineer, you will have to use rec... More on crazyengineers.com
🌐 crazyengineers.com
0
December 1, 2008
Getting out of a recursive function... - Post.Byes - Bytes
Hi, I have a function, looks a bit like this: def function(): if condition: do stuff, including a few recursive calls (to function()), this 'stuff' also changes the state of 'condition'. 'condition' is a global list. else: I want to break out of the function and move on To break out I have tried More on post.bytes.com
🌐 post.bytes.com
python - How to break out of recursive function? - Stack Overflow
I want to stop the recursive function as soon as I find an integer. An example list would be: [[[1.2, 2.3, 3.3], [4.3, [[5]]]], 6.3] def flatten(arr): for elem in arr: if isinstance(elem, collections.Iterable) and not isinstance(elem, (str, bytes)): return flatten(elem) else: if not isinstance(elem, float): # break ... More on stackoverflow.com
🌐 stackoverflow.com
How do I break out of loops in recursive functions?
I'm working with a array of category objects that can have an array of child category objects. The tricky part is that the depth of this nested data is unknown (and can change). (See sample at bott... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
🌐
Reddit
reddit.com › r/cpp_questions › how to break out of recursion and return a value without having it reset "on its way back"
r/cpp_questions on Reddit: How to break out of recursion and return a value without having it reset "on its way back"
April 14, 2021 -

So currently, I solved the issue with a global variable that won't change, but I feel dirty not properly solving this.

So in short, I have a binary tree with nodes, a node holds a key (name) and data.

I have a "find" function that is supposed to find a node with a given key, and return its data. Problem is, when I find it, I set the returning value to the data, but as it keeps recursively returning back this value (or pointer) is set to null, because I assume I just made a local change in the function call that found the node?

I traverse the tree using "inorder traversal".

double* find_key(Node * & p, int key_to_be_found, double* dataReturn)
{
    if (p == NULL)
        return dataReturn;
 
    find_key(p->left, key_to_be_found, dataReturn);//Left
 
    
    if(key_to_be_found == p->key) //Visit
    {
        dataReturn = &p->data;
        return;
    }
 
    find_key(p->right, key_to_be_found, dataReturn);//Right
}

Note: it works for the nodes in the right subtree, but not for the nodes in the left subtree. My guess is that it has to do with it "returning backwards" for the left subtree, thus returning a different "dataReturn" then what I set, as I chose inorder traversal.

🌐
Medium
medium.com › @swellpf › understanding-recursion-doesnt-have-to-keep-you-stuck-in-a-loop-here-s-how-to-break-out-99ad189e78cd
Understanding Recursion Doesn’t Have to Keep You Stuck in a Loop. Here’s How to Break Out. | by Paul Cinoman | Medium
August 25, 2021 - A properly constructed recursive function consists of two components. The first is called the base case. The base case identifies the condition that will cause the loop to exit. The second requirement is that the input the function receives is different as the loop repeats and at some point reaches the base case. Each time the function is called it will be added to the call stack waiting to be executed. Once the base case is reached, each call is processed from the top of the stack in LIFO (last in, first out) order.
🌐
CrazyEngineers
crazyengineers.com › home › threads › how to stop recursion function?
How to Stop Recursion Function? | CrazyEngineers
December 1, 2008 - Thanks a lot for your answer..and also does the recursion function forms an infinite loop??? Its clear that we can terminate the recursive function either by a break,goto,and return functions..
🌐
Post.Byes
post.bytes.com › home › forum › topic › python
Getting out of a recursive function... - Post.Byes - Bytes
Hope this is what you wanted to ... loop. A while loop will continuously execute all the code inside while the condition is true. Also the keyword break will exit the loop....
🌐
Quora
quora.com › How-come-I-can-break-out-of-recursion-with-the-pass-keyword-in-Python
How come I can break out of recursion with the 'pass' keyword in Python? - Quora
Answer (1 of 4): You can’t break out of the look with “pass”, but you could confuse yourself into thinking this loop is doing just that. Actually it is doing nothing - you can just delete the else… [code]def rec(n): if n: rec(n-1) else: pass rec(10) [/code]
Find elsewhere
🌐
Cornell Computer Science
cs.cornell.edu › courses › cs1110 › 2017fa › lectures › 10-17-17 › handout-16.pdf pdf
10/15/17 1 Example: Reversing a String def reverse(s): """Returns: reverse of s
October 15, 2017 - How to Break Up a Recursive Function? def exp(b, c) """Returns: bc · Precondition: b a float, c ≥ 0 an int""" Approach 1 · Approach 2 · 12256 = 12 × (12255) Recursive · 12256 = (12128) × (12128) Recursive · Recursive · bc = b × (bc-1) bc = (b×b)c/2 if c even ·
🌐
Tek-Tips
tek-tips.com › home › forums › software › programmers › languages › c++
escaping out of recursive function | Tek-Tips
January 5, 2003 - Or, if it's an infinite recursive you could set some kind of boolean flag to prevent recalls. programmer (prog'ram'er), n A hot-headed, anorak wearing, pimple-faced computer geek.​ ... This assumes you have functions for returning the data of the root, as well as the data of the left and right children.
🌐
Reddit
reddit.com › r/learnpython › how to exit a recursive function loop?
r/learnpython on Reddit: How to exit a recursive function loop?
January 25, 2021 -

Hey pals,

I am very overwhelmed about this homework i've been working on. Searched the web for solutions but couldn't find anything helpful.

So the goal is to define a function that determines if a number is a happy number (if a number reaches finally to 1, when sum of its squared digits transformed repeatedly, it is a happy number; see below).

>Step 1: Transform 139
>
>1² + 3² + 9² = 1 + 9 + 81 = 91
>
>Step 2: Transform 91
>
>9² + 1² = 81 + 1 = 82
>
>Step 3: Transform 82
>
>8² + 2² = 64 + 4 = 68
>
>Step 4: Transform 68
>
>6² + 8² = 36 + 64 = 100
>
>Step 5: Transform 100
>
>1² + 0² + 0² = 1 + 0 + 0 = 1
>
>The algorithm stops at step 5: 139 is a Happy number

​

  1. I have to write this as a recursive function but it keeps going into infinite loops? How can i avoid this?

  2. I need to return number of steps required to reach the final result. How can i add this to my code?

Besides, i am a newbie coder so any help and advice about coding in general and about this issue in particular are appreciated.

ps: not a native English speaker.

def digitsOf(num):
    digits = []
    while num > 0:
        rem = num % 10
        num = (num - rem)/10
        digits.append(int(rem))
    return digits

def number_detection(num):
    
    digits = digitsOf(num) 
    summ = 0
    
    for number in digits:
        summ += number**2
        
    result = False
    
    if summ == 1:
       result = True 
       
    elif summ == num:
        result = False

    else:
        if number_detection(summ) == True:
            result = True
    
    return result
  
def isNumberHappy(num):
    if number_detection(num) == True:
        print(num,"is a happy number")
    
    elif number_detection(num) == False:
        print(num, "is a sad number")
Top answer
1 of 3
2
So you need to return number of steps AND if it's happy or sad? Right now you are using the return stack to return the happy or sad result. One way to do this would be to return a tuple instead, with (result, num_steps). def digitsOf(num): digits = [] while num > 0: rem = num % 10 num = (num - rem)/10 digits.append(int(rem)) return digits def number_detection(num, steps=1): digits = digitsOf(num) summ = 0 for number in digits: summ += number**2 result = False, steps if summ == 1: result = True, steps elif summ == num: result = False, steps else: result = number_detection(summ, steps+1) return result def isNumberHappy(num): happy, num_steps = number_detection(num) if happy == True: print(f"{num} is a happy number with {num_steps} steps.") else: print(num, "is a sad number") Another way to do this is to use the return stack for the num_steps only, and raise an error if the number is sad.
2 of 3
2
number_detection is already recursive, because it calls itself in line 26. If you literally aren't allowed to use any loops, then you need to get rid of the ones in line 3 and 14. Keep in mind you don't need to use recursion just because you're not going to use a loop - for example, your digitsOf function is fine; normally I would convert a number to a list of its numerals by just writing tuple(int(character) for character in str(the_number)). Technically that might still contain a for loop, I guess; so you could write something like list(map(int, str(the_number)))? IMO this is kind of getting into the domain of "proving I can do something" and out of the domain of "good code."
Top answer
1 of 2
2

The function combo I was looking for is CATCH/THROW. Once again, using the given function:

walk: func [series [block!] criteria [block!]][
    use [value] compose/deep [
        while [not tail? series][
            value: pick series 1

            either block? value [
                walk value criteria
            ][
                (to paren! criteria)
            ]

            series: next series
        ]
    ]
]

I can simply wrap it as follows:

catch [walk [a [b c [d e] f] g] [if value = 'e [throw value]]]
; returns 'e

Some Notes

  • I want the function to return NONE if there are no matches

I'll just have WALK return NONE (am using ALSO just so as not to leave an awkward trailing none):

 walk: func [series [block!] criteria [block!]][
      also none use [value] compose/deep [
          while [not tail? series][
              value: pick series 1

              either block? value [
                  walk value criteria
              ][
                  (to paren! criteria)
              ]

              series: next series
          ]
      ]
  ]
  • red does not have a USE function

This introduces a complication as I only want to bind the block to the word VALUE. If I were to rewrite the function as follows:

walk: func [series [block!] criteria [block!] /local value][
    do bind compose/deep [
        while [not tail? series][
            value: pick series 1

            either block? value [
                walk value criteria
            ][
                (to paren! criteria)
            ]

            series: next series
        ]
    ] 'value
]

Then it also binds that same block to the words SERIES and CRITERIA which would override the binding of any such words from the calling context, e.g.:

walk [some values][series: none probe value] ; results in error
2 of 2
2

This version avoids binding anything except VALUE and works in Red 0.6.3 and Rebol2:

walk: func [series [block!] criteria [block!]][
    also none do bind compose/deep [
        while [not tail? series] [
            value: pick series 1
            either block? value [
                walk value criteria
            ] [
                (to paren! criteria)
            ]
            series: next series
        ]
    ]
    context [value: none]
]

(Comments on how this implementation differs from what USE does would be welcome.)

And yes, this does not work on Rebol3 Alpha. But neither does the one with the USE. I think it's a THROW issue.

🌐
Oracle
forums.oracle.com › ords › apexds › post › breaking-out-of-a-recursion-4027
breaking out of a recursion - Oracle Forums
January 9, 2009 - hello all, I have a recursive method in a java program. the main program contains a for loop which calls the recursive method for a certain number of times. the recursive method obviously calls itse...