变量解析 LEGB

  1. In [4]: x = 5
  2. In [5]: def foo(x =6, y=7):
  3. ...: nonlocal x
  4. File "<ipython-input-5-89de33a38c80>", line 2
  5. nonlocal x
  6. ^
  7. SyntaxError: name 'x' is parameter and nonlocal
  8. In [6]: def foo(x = 6, y=7):
  9. ...: def foo2(a=10, b=11):
  10. ...: nonlocal x
  11. ...: x = 5
  12. ...: return x
  13. ...: return x
  14. ...:
  15. In [7]: foo(6, 7)
  16. Out[7]: 6
  17. In [8]:
  18. In [8]: foo(y=7)

python 递归函数

  1. import dis
  2. dis.dis('''
  3. def foo1(b, b1=3):
  4. '''
  5. 函数执行过程字节码
  6. '''
  7. print('foo1 called', b, b1)
  8. foo2(2)
  9. def foo2(a):
  10. pass
  11. ''')

编写递归程序:
a. 直接/间接调用自身
b. 递归需要有边界条件,递归前进段,递归返回段
c. 一定要有边界条件
当边界不满足时候,递归前进
当边界满足的时候,递归返回

python关于递归的限制
import sys
sys.getrecursionlimit()
sys.setrecursionlimit()

使用递归打印斐波那契数列

  1. 使用循环打印
    pre = 0
    cur = 1
    print(pre, cur, end = ‘ ‘)
    n = 10
    for i in range(2, n):
    pre, cur = cur, pre + cur
    print(cur, end = ‘ ‘)
    def pfib(n):
    pre = 0
    cur = 1
    print(pre, cur, end =’ ‘)
    for i in range(n-2):
    pre, cur = cur, pre+cur
    print(cur, end = ‘ ‘)
  2. 使用递归函数打印
    def fib(n):
    ‘’’
    f(0) = 0, f(1) = 1, f(n) = f(n-1) + f(n-2)
    ‘’’
    if n == 0: return 0
    if n == 1: return 1
    return fib(n-1) + fib(n-2)
    def fib2(n):
    return 1 if n < 2 else fib2(n-1) + fib2(n-2)
    def fib3(n, pre=0, cur=1):
    ‘’’类似循环,n为边界’’’
    pre, cur = cur, pre+cur
    print(cur, end=’ ‘)
    if n == 1:
    return
    fib3(n-1, pre, cur)

fib函数时间复杂度O(2N)

  1. '''递归练习代码'''
  2. def fib5(n, pre=0, cur=1):
  3. if pre == 0: print(pre,cur, end = ' ')
  4. pre, cur = cur, pre+cur
  5. print(cur, end =' ' )
  6. if n == 2: return
  7. fib5(n-1, pre, cur)
  8. In [134]: fib5(10)
  9. 0 1 1 2 3 5 8 13 21 34 55
  10. def fib6(n, pre=0, cur=1):
  11. if pre == 0: print(pre, cur, end = ' ')
  12. pre, cur = cur, pre+cur
  13. print(pre, end = ' ')
  14. if n == 2: return
  15. fib6(n-1, pre, cur)
  16. fib6(10)
  17. def fib6(n, pre=0, cur=1):
  18. if pre == 0: print(pre, end = ' ')
  19. pre, cur = cur, pre+cur
  20. print(pre, end = ' ')
  21. if n == 2: return
  22. fib6(n-1, pre, cur)
  23. fib6(10)

base64_table
0 ~25 A~Z
26~51 a~z
52~61 0~9
62 +
63 /