递归就是在过程或函数里调用自身,在使用递归策略时,必须有一个明确的递归结束条件,称为递归出口,递归算法解题通常显得很简洁,但递归算法解题的运行效率较低。在递归调用的过程当中系统为每一层的返回点、局部量等开辟了栈来存储,递归次数过多容易造成栈溢出等,所以一般不提倡用递归算法设计程序。
1 #一个简单的递归 2 def calc(n): 3 print(n) 4 if n/2 >1: 5 res = calc(n/2) 6 return res 7 8 calc(10) 9 #输出结果 10 10 11 5.0 12 2.5 13 1.25
斐波那契数列,0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765
1 def data(arg1,arg2,stop): 2 if arg1 == 0: 3 print(arg1) 4 arg3 = arg1+arg2 5 print(arg3) 6 if arg3 < stop: 7 data(arg2,arg3,stop) 8 data(0,1,6765)
二分查找
现有列表data=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,......999,1000],1000个数字,要快速查找到678
实现方法:从列表从中截取一半,分成两个列表,判断678在哪个列表中,把列表再截取一半,直到查找到678
1 def search(source,find_n): 2 mid = int(len(source)/2) 3 if len(source) >= 1: 4 #print(len(source)) 5 if source[mid] > find_n: 6 print("data in left of [%s]" %source[mid]) 7 #print(source[:mid]) 8 search(source[:mid],find_n) 9 elif source[mid] < find_n: 10 print("data in right of [%s]" %source[mid]) 11 #print(source[mid:]) 12 search(source[mid:],find_n) 13 else: 14 print("find",source[mid]) 15 else: 16 print("cannot find...") 17 if __name__=='__main__': 18 data = list(range(1,1000)) 19 search(data,678)
生成一个4*4的2维数组并将其顺时针旋转90度
1 a = [[colo for colo in range(4)]for row in range(4)] 2 for i in a: 3 print(i) 4 5 for r,row in enumerate(a): 6 for c in range(r,len(row)): 7 tmp = a[c][r] 8 a[c][r] = a[r][c] 9 a[r][c] = tmp 10 print('------------') 11 for b in a: 12 print(b) 13 14 #另一种方法 15 for i in range(len(a)): 16 print(i) 17 f = [a[i][i] for row in range(4)] 18 print(f)
冒泡算法
对下列数组进行从小到大排列:data=[10,4,33,21,54,3,8,11,5,22,2,1,17,13,6],前一个数和后一个数进行比较,数值大的向后移
1 data = [10,4,33,21,54,3,8,11,5,22,2,1,17,13,6] 2 for j in range(1,len(data)): 3 for i in range(len(data)-j): 4 if data[i] > data[i+1]: 5 tmp = data[i] 6 data[i] = data[i+1] 7 data[i+1] = tmp 8 print(data) 9 #输出结果[1, 2, 3, 4, 5, 6, 8, 10, 11, 13, 17, 21, 22, 33, 54]