Δ汉诺塔例子
# 定义三个全局的列表 la = [] lb = [] lc = [] stepn = 0 def create_hano(n): '''构建由n个圆盘组成的汉诺塔''' global la la = [i for i in range(n, 0, -1)] def move(src, dest): '''从src柱子上最上面的圆盘移动到dest柱子上''' dest.append(src.pop()) global stepn stepn += 1 input() print('柱子A:',la) print('柱子B:',lb) print('柱子C:',lc) def start_game(src, tmp, dest, n): if n == 1: move(src, dest) return None if n < 1: return -1 start_game(src, dest, tmp, n-1) start_game(src, tmp, dest, 1) start_game(tmp, src, dest, n-1) create_hano(4) print('柱子A:',la) print('柱子B:',lb) print('柱子C:',lc) start_game(la, lb, lc, 4) print(stepn)
- 生成器(generator):
- 迭代器(Iterator):
next()得到成员的:generator
- 可迭代(Iterable):
能用for遍历的:str, list, tuple, dict, set, generator, range
collections模块中定义的Iterator和Iterable类型
# 从1开始的fib def fib(n): a, b = 0, 1 while n > 0: # print(b) yield b # 随着生成器调用next方法,得到yield的值 a, b = b, a+b n -= 1 return 'done' g = fib(10) print(g)
- 匿名函数 lambda : 适合函数功能简洁的
f = lambda x : True if x % 2 == 0 else False print(type(f)) print(f(101)) f = lambda : print('hello world') f() f = lambda x, y : x * y print(f(10, 14)) f = lambda x, y=2 : x ** y print(f(5, 5)) f = lambda x, *arg : print(x, arg) print(f(1, 2,3,4,5,6))
- 高阶函数:函数为参
- map():对多个参数进行同一操作
def test(n): return n ** 3 # g = map(test, (1,2,3,4)) g = map(lambda x : x**3, (1,2,3,4)) print(type(g)) print(next(g)) print(next(g)) print(next(g)) ''' for res in g: print(res) ''' l = list(g) print(l)
''' 练习1: 生成一个由5个10以内随机整型数组成的列表,使用高阶函数map实现将5个整型数分别转换为字符串 ''' import random l = [random.randrange(10) for i in range(5)] print(l) l = list(map(str, l)) print(l) ''' 练习2: 将列表中每一个元素都转换为一个标准的标题,首字符大写其它小写 l = ['hello world', 'Good AFTERNOON', 'morning'] ''' l = ['hello world', 'Good AFTERNOON', 'morning'] l = list(map(lambda x : x.title(), l)) print(l)
- filter():过滤
res = filter(lambda x : x % 2 == 0, [random.randrange(100) for i in range(10)]) print(list(res))
- sorted():排序,有key值默认为NONE
l = ['hello', 'Yes', 'PYTHON', 'world', 'Go'] res = sorted(l, key=str.lower, reverse=True) # 按小写排序 print(res)
- reduce() :两个变量后跟类型 functools
from functools import reduce def f(x, y): return x * 10 + y n = reduce(f, (1,5,6,7)) print(type(n), n) n = reduce(lambda x,y : x*y, (1,2,3,4,5,6)) print(n)
'''
实现一个将字符串转换为整型数的函数str2int()
'1432' ----> 1432 不允许调用int函数
'''
def str2int(s):
g = map(lambda x:ord(x)-ord('0'), s)
return reduce(lambda x, y:x*10+y, g)
print(str2int('1423'))
- 装饰器(decorator):修饰函数
import datetime d = datetime.date() print(d) ''' # 函数作为返回值 def test(): return str f = test() print(f(1234)) import functools def decorator(f): @functools.wraps(f) # 此装饰器作用是将f的函数名赋值给wrapper def wrapper(*args, **kw): '''装饰器的内部函数''' # print(args, kw) print('hello python') # print(f.__name__) return f(*args, **kw) return wrapper @decorator def show(name1, name2): '''验证装饰器功能的小函数''' print('hello %s and %s' % (name1, name2)) return 100 print(show.__name__) print(show.__doc__) res = show('aa', 'bb') # show = decorator(show) print(res)
带参数的装饰器
import functools def log(text, text2): def decorator(f): @functools.wraps(f) def wrapper(*args, **kw): print('log', text, text2) print('这个装饰器好吧?') return f(*args, **kw) return wrapper return decorator @log('argument', 'haha') def now(): print('2018-12-12') now() # now = log('argument')(now)