- 数列:
- a = a1,a2,a3,·····,an
- b = b1,b2,b3,·····,bn
- 求:
- c = a12+b13,a22+b23,a32+b33,·····+an2+bn3
1.用列表+循环实现,并包装成函数
2.用numpy实现,并包装成函数
3.对比两种方法实现的效率,给定一个较大的参数n,用运行函数前后的timedelta表示。
#列表+循环 实现,并包装成一个函数 def mysum(n): d = list(range(n)) b = list(range(0,5*n,5)) c= [] for i in range(len(d)): c.append(d[i]**2 + b[i]**3) return(c) print(mysum(10)) #用numpy直接相加 import numpy def npsum(n): a = numpy.arange(n) b = numpy.arange(n) c = a**2+b**3 return c print(npsum(10)) from datetime import datetime start = datetime.now() mysum(1000000) dalta =datetime.now()-start print(dalta) start = datetime.now() npsum(1000000) delta = datetime.now()-start print(delta)
运行结果: