[关闭]
@Lin-- 2018-09-26T14:41:24.000000Z 字数 978 阅读 271

两种数列求积算法的分析比较

计算机数学


1.逐个相乘

  1. def product1(x):
  2. res=1
  3. count=0
  4. for i in range(len(x)):
  5. res=res*x[i]
  6. count=count+1
  7. return res,count
  8. #测试
  9. list1=[1,2,3,4,5]
  10. list2=[2]
  11. list3=(range(1000000))
  12. list4=(range(0))
  13. print(product1(list1),product1(list2),product1(list3),product1(list4))

算法效率:O(n)

运算过程遍历列表的每一项,故当输入规模为n时,需进行n次运算。

实验数据:

2.递归

  1. a=0
  2. def product2(x):
  3. global a
  4. if len(x)==0:
  5. a=0
  6. return 1
  7. if len(x)==1:
  8. a=a+1
  9. return x[0]
  10. if len(x)==2:
  11. a=a+2
  12. return x[0]*x[1]
  13. l=len(x)
  14. return product2(x[0:(l+1)//2])*product2(x[(l+1)//2:l])
  15. #测试
  16. list1=[1,2,3,4,5]
  17. list2=[2]
  18. list3=(range(1000000))
  19. list4=(range(0))
  20. print(product2(list1),a)
  21. a=0
  22. print(product2(list2),a)
  23. a=0
  24. print(product2(list3),a)
  25. a=0
  26. print(product2(list4),a)

算法效率:








实验数据:

120 5
2 1
0 1000000
1 0

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注