# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ # ============================================================================= #练习 # 汉诺塔的移动可以用递归函数非常简单地实现。 # # 请编写move(n, a, b, c)函数,它接收参数n,表示3个柱子A、B、C中第1个柱子A的盘子数量,然后打印出把所有盘子从A借助B移动到C的方法,例如: # # ============================================================================= # -*- coding: utf-8 -*- def move(n, a, b, c): if n == 1: print(a, '-->', c) else: move(n-1,a,c,b) print(a, '-->', c) move(n-1,b,a,c) move(3, 'A', 'B', 'C') move(4, 'A', 'B', 'C') #高级特性 L=[] n=1 while n<=99: L.append(n) n=n+1 L1=range(99) L1=list(range(99)) L1.append(99) L1.pop(0) # ============================================================================= # 切片 # ============================================================================= L=['Michael','Sarah','Tracy','Bob','Jack'] [L[0],L[1],L[2]] r=[] n=3 for x in range(n): r.append(L[x]) #切片[n:m]表示,从索引n开始取,直到索引m-1为止,但不包括索引m。 L[0:3]#从0开始直到索引到L[2] L[1:4] #从头索引0可以省略 L[:4] #倒数切片 L[-2:] L[-2:-1] L=list(range(100)) L[:10]#前10个数 L[-10:]#后10个数 L[10:20]#11-20数 L[:10:2]#前十个数字每两个取一个 L[::5]#所有数字5个取一个 L[:]#原list #tuple也可看做list (1,2,3,4,5)[:3] #字符串也可以 'ABCDEFGH'[1:3] 'ABCDEFGH'[::2] # ============================================================================= # 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法: # ============================================================================= def trim(s): if len(s) ==0: return '' while s[0]==' ': if len(s)==1: return '' s=s[1:] while s[-1]==' ': s=s[:-1]#截取到倒数第一个之前的数字不包含倒数第一个 return s # ============================================================================= # 迭代 # ============================================================================= #dictionary 迭代 d={'a':1,'b':2,'c':3} for key in d: print(key) for value in d.values(): print(value) for key,value in d.items(): print(key,value) #字符串迭代 for character in 'string': print(character) #判断是否可迭代对象:通过collections模块的Iterable类型判断 from collections import Iterable isinstance('abc', Iterable) isinstance([1,2,3],Iterable) isinstance(123, Iterable) #enumerate函数 迭代引用索引 i=0 for i , value in enumerate(['A','B','C']): print(i,value) for value in ['A','B','C']: print (i , value) i=i+1 #双变量迭代 for x,y in[(1,1),(2,2),(3,3)]: print(x,y) # ============================================================================= # 请使用迭代查找一个list中最小和最大值,并返回一个tuple: # ============================================================================= def findMinAndMax(L): if len(L)==0: return None,None else: MIN=L[0] MAX=L[0] for x in L: if MIN>=x: MIN=x if MAX<=x: MAX=x return MIN,MAX # ============================================================================= # 列表生成式List Comprehensions # ============================================================================= #要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11)): L=list(range(1,11)) #要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做? L=[] for x in list(range(1,11)): L.append(x*x) #超快的方式[函数式,迭代语句,条件语句] L=[x*x for x in range(1,11)] L=[x*x for x in range(1,11) if x%2==0] #两次迭代 #ABC的全排列 L=[m+n for m in 'ABC' for n in 'ABC' if m!=n] L=[j+k+l for j in 'ABC' for k in 'ABC' for l in 'ABC' if j is not l and j is not k and k is not l] #目录下所有文件以及目录名字 import os [d for d in os.listdir('c:/')] #dictionary的列表生成 d={'x':'A','y':'B','z':'C'} for key,value in d.items(): print(key,'=',value) [key+'='+value for key,value in d.items()] #把list变成小写 L=[j+k+l for j in 'ABC' for k in 'ABC' for l in 'ABC' if j is not l and j is not k and k is not l] [s.lower() for s in L] # ============================================================================= # 如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错: # 使用内建的isinstance函数可以判断一个变量是不是字符串: # >>> x = 'abc' # >>> y = 123 # >>> isinstance(x, str) # True # >>> isinstance(y, str) # False # 请修改列表生成式,通过添加if语句保证列表生成式能正确地执行: # ============================================================================= L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [s.lower() for s in L1 if isinstance(s, str)==True] # 测试: print(L2) if L2 == ['hello', 'world', 'apple']: print('测试通过!') else: print('测试失败!') # ============================================================================= # 生成器generator # 在Python中,这种一边循环一边计算的机制,称为生成器:generator。 # ============================================================================= #要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator: L=[x*x for x in range(10)] L g=(x*x for x in range(10)) g #通过next()函数获得generator的下一个返回值: next(g) next(g) next(g) next(g) next(g) next(g) next(g) next(g) next(g) next(g) next(g) g=(x*x for x in range(10)) for n in g: print(n) #斐波拉契数列(Fibonacci) def Fibonacci(n,a=1,b=1): i=1 print(a) while i<n: print(b) i,a,b=i+1,b,a+b return 'Done' #斐波拉契数列(Fibonacci)生成器generator def Fibonacci2(n,a=1,b=1): i=1 print(a) while i<n: yield(b) i,a,b=i+1,b,a+b return 'Done' f=Fibonacci2(6) for x in f: print(x) #变成generator的函数,在每次调用next()的时候执行, #遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。 def odd(): print('step 1') yield 1 print('step 2') yield 2 print('step 3') yield 3 o=odd() next(o) next(o) next(o) next(o) #但是用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中: g=Fibonacci2(6) while True: try: x=next(g) print('g:',x) except StopIteration as e: print('Generator return value:',e.value) break # ============================================================================= # 练习 # 杨辉三角定义如下: # # 1 # / \ # 1 1 # / \ / \ # 1 2 1 # / \ / \ / \ # 1 3 3 1 # / \ / \ / \ / \ # 1 4 6 4 1 # / \ / \ / \ / \ / \ # 1 5 10 10 5 1 # 把每一行看做一个list,试写一个generator,不断输出下一行的list: # ============================================================================= def triangles(t=20): L=[1] while len(L)<20: yield L i=1 L1=[1,1] while i < len(L): L1.insert(i,L[i-1]+L[i]) i=i+1 L=L1 #简洁写法: def triangles1(): list = [1] while True: yield (list) list = [1]+[ list[i]+list[i+1] for i in range(len(list)-1)] +[1] # 期待输出: # [1] # [1, 1] # [1, 2, 1] # [1, 3, 3, 1] # [1, 4, 6, 4, 1] # [1, 5, 10, 10, 5, 1] # [1, 6, 15, 20, 15, 6, 1] # [1, 7, 21, 35, 35, 21, 7, 1] # [1, 8, 28, 56, 70, 56, 28, 8, 1] # [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] n = 0 results = [] for t in triangles(): results.append(t) n = n + 1 if n == 10: break for t in results: print(t) if results == [ [1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] ]: print('测试通过!') else: print('测试失败!')
浙公网安备 33010602011771号