Home > Software engineering >  How to generalize my function in iteration or recursion type?
How to generalize my function in iteration or recursion type?

Time:09-20

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

I want to return a result that its length is larger than 1 and after 4 times, if it still less than 1, that is enough, then return the result that smaller than 1. 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!

CodePudding user response:

To repeat an action several times, use a loop. Either a for-loop or a while-loop. If you know the number of times in advance, use a for-loop; if you don't, use a while-loop.

Here we don't know in advance; so we use a while-loop:

def checkif(s1):
    r1 = extract(s1)
    extracted_times = 1
    while len(r1) < 1 and extracted_times < 4:
        r1 = extract(s1)
        extracted_times  = 1
    return r1

Note that if s1 doesn't change between two calls to extract, then we should expect that extract will always produce the same result. Trying to extract more than once only makes sense if extract does not always produce the same result, either because it is influence by randomness or external factors, or because it modifies its input in addition to producing an output.

Usually, it's good to make it very explicit whether a function produces a result, or modifies its input. For instance, consider sorted(l) which produces a sorted list without modifying its input; and l.sort() which sorts its input without producing a result. Mixing those two kinds of functions can defy the expectations of the user and cause mistakes.

CodePudding user response:

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.

  • Related