Stair climbing problems, yield learning summary

The origin of the problem:

A person climbing stairs, step by step can be one, two, if there are N-level stairs, programming requirements, seeking a total of how many moves.

A simple recursive thought, as long as the N-1 layer climb, climb or N-2 layer, the next step is asserted only one walk. Therefore, the first two steps go looking N-1, N-2 is. Dynamic programming equation: f (n) = f (n-1) + f (n-2)

 

plan 1:

DEF climb_2 (n-):   # is very slow 
    IF n- Not  in [. 1, 2 ]:
         return climb_2 (n--. 1) climb_2 + (n-- 2 )
     the else :
         return n-

But the run down, you will find, climb_2 (3) = 3 as early as the beginning of this value has been calculated, but behind climb_2 (4) as well as all subsequent recursion will go to recalculate this value. When nesting complicated, we do a lot of duplication of effort, poor speed.

 

Scenario 2:

dict_t = {1:1, 2:2}
def climb_1(n):
    global dict_t
    if n not in dict_t.keys():
        dict_t[n - 1] = climb_1(n - 1)
        dict_t[n - 2] = climb_1(n - 2)
        dict_t[n] = dict_t[n - 1] + dict_t[n - 2]
    return dict_t[n]
 

Although this is recursively nested, but with global dict_t dictionaries do storage, will no longer be silly climb_2 (3) recalculate, be sure to optimize the level. But then there is a drawback: You must rely on nonlocal or global variable outside the function.

Scenario 3:

@functools.lru_cache(3)
def climb_3(n):
    if n not in [1, 2]:
        return climb_3(n - 1) + climb_3(n - 2)
    else:
        return n

Such programs also learn functools recently discovered, there is a lru_cache cache function can return values, ideas also with Option 2, but more elegant, and highly capable, but also free from dependence nonlocal variables. But there's a problem not understand. 3 cache size on why fast enough, but two is not enough. Here to leave a question mark?

 

Scenario 4:

def climb_4(n):
    def inner():
        (a, b) = (1, 2)
        yield a
        yield b
        while 1:
            yield (a + b)
            (a, b) = (b, a + b)
            
    bo = inner()
    for _ in range(n):
        s = next(bo)
    return s

Scheme 4 uses yield keyword (last appreciated scholarship), i.e. generator. yield can be seen as a special return, but when entering this method again, will continue to yield from the archive at the meeting. It has saved variable results.

After inspired by this layer, the preparation of the above embodiment, is n-1, n is 2, the two set points, the yield out of a a, yield out of a b. . After a 1, 2, we enter an infinite loop stage. A + b will generate out, when the re-entry to the function, and then resume a and b assignment. Overall looks good kind of program.

 

 

Guess you like

Origin www.cnblogs.com/july401/p/11286212.html