Python技巧100题(九)


  • 1.不使用递归,怎么高效写出阶乘表达式
  • 2.Python什么时候执行装饰器
  • 3.判断下面语句执行是否会报错
  • 4.怎么强制把函数中局部变量变成全局变量
  • 5.闭包中怎么对数字、字符串、元组等不可变元素更新
  • 6.Python2怎么解决访问外部变量报错的问题
  • 7.测试代码运行的时间
  • 8.怎么优化递归算法,减少执行时间
  • 9.比较两个对象的值(对象中保存的数据)是否相等
  • 10.比较两个对象的内存地址id是否相等

1.不使用递归,怎么高效写出阶乘表达式

from functools import reduce
from operator import mul
def fact(n):
    return reduce(nul, range(1 ,n+1))
print(fact(5))
120    

2.Python什么时候执行装饰器

registry = []

def register(func):
    print('running register(%s)' % func)
    registry.append(func)
    return func

@register
def f1():
    print('running f1()')

@register
def f2():
    print('running f2()')

def f3():
    print('running f3()')

def main():
    print('running main()')
    print('registry ->', registry)
    f1()
    f2()
    f3()

if __name__ == '__main__':
    main()

running register(<function f1 at 0x0000027913AA8708>)
running register(<function f2 at 0x0000027913AA8E58>)
running main()
registry -> [<function f1 at 0x0000027913AA8708>, <function f2 at 0x0000027913AA8E58>]
running f1()
running f2()
running f3()

3.判断下面语句执行是否会报错

b = 3
def fun(a):
    print(a)
    print(b)
    b = 7
fun(2)    

4.怎么强制把函数中局部变量变成全局变量

b = 3
def fun(a):
    global b
    print(a)
    print(b)
    b = 7
b = 5
fun(2)
2
5    

5.闭包中怎么对数字、字符串、元组等不可变元素更新

def make_averager:
    count = 0
    total = 0
def averager(new_value):
    nonlocal count, total
    count += 1
    total += new_value
    return total / count
return averager
avg = make_averager()
avg(10)
10.0        

6.Python2怎么解决访问外部变量报错的问题

https://www.python.org/dev/peps/pep-3104/

7.测试代码运行的时间

import time
t0 = time.time()
for i in range(10000):
    pass
t1 = time.time()
print(t1 - t0) 

t0 = time.perf_count()
for i in range(10000):
    pass
t1 = time.perf_count()
print(t1 - t0)       

8.怎么优化递归算法,减少执行时间

import functools
@functools.lru_cache()
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-2)+fibonacci(n-1)
fibonacci(6)
8        

9.比较两个对象的值(对象中保存的数据)是否相等

a = [1, 2, 3]
b = [1, 2, 3]
a == b
True

10.比较两个对象的内存地址id是否相等

a = [1, 2, 3]
b = [1, 2, 3]
print(a is b)
False

你可能感兴趣的:(Python技巧)