[SOLVED] How to generalize my function in iteration or recursion type?

Issue

This Content is from Stack Overflow. Question asked by 4daJKong

I have two functions,and their structure like that,

def extract(input):
    pass  #test the length of input, and the length changed over time

def checkif(s1):
    r1 = extract(s1)
    if len(r1) < 1:
        r1 = extract(s1)
        if len(r1) < 1:
            r1 = extract(s1)
            if len(r1) < 1:
                r1 = extract(s1)
                return r1
            else:
                return r1
        else:
            return r1
    else:
        return r1

you see, the function of checkif is complex and I think it can be reduced, but how to reduce this structure? Any idea is helpful!



Solution

If you need to limit it to 4 times, you could use a for-loop:

def checkif(s1):
    for _ in range(3):
        r1 = extract(s1)
        if len(r1) >= 1:
            return r1
    return extract(s1)

Notice I loop 3 times because the last time you return r1 unconditionally, which happens outside of the loop.


This Question was asked in StackOverflow by 4daJKong and Answered by Jasmijn It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?