defproduct(*number): if number == (): raise TypeError a = 1 for x in number: a = x*a return a
递归函数
1 2 3 4 5 6 7 8
defmove(n, a, b, c): if n == 1: print ( a , '-->' , c) else: move(n-1,a,c,b) #假设move函数没问题,A上前n-1个会被移动至B move(1,a,b,c) #此时把最大的放到C move(n-1,b,a,c) #move(4,'A','B','C')
切片
1 2 3 4 5 6 7 8 9 10
deftrim(s): if s == '': return s while s[0] == ' ': s = s[1:] if s == ' ': return'' while s[-1] == ' ': s = s[0:-1] return s
迭代
1 2 3 4 5 6 7 8 9 10 11 12
deffindMinAndMax(L): if L == []: return (None,None) else: a = L[0] b = L[0] for i in L: if i < a: a = i if i > b: b = i return (a,b)
列表生成式
1 2
L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [ x.lower() for x in L1 ifisinstance(x,str) ]
生成器
1 2 3 4 5 6 7 8 9 10 11 12 13 14
deftriangles(): n = 2 a = [1,1] b = [1] yield [1] yield [1,1] while1: for i inrange(1,n): b.append(a[i] + a[i-1]) b.append(1) n = n+1 a = b b = [1] yield a