import time
def func(a, x):
"""秦九韶算法计算n次多项式的值"""
result = a[-1]
r_fac = a[::-1] # 列表倒序
for i in r_fac[1:]:
result = result*x + i
return(result)
a = [3, 8, 5, 0, 7, 1] # 自行输入的系数列表
time_begin = time.time() # 程序开始算法的时间
print(func(a, 1)) # 此处x取1
time_end = time.time() # 程序结束算法的时间
time = time_end - time_begin # 两者之差就是算法所消耗的时间
print("tiem: ", time)
import time
def func_1(a, x):
"""常规方法"""
result = a[0]
for factor in a[1:]:
i = a.index(factor) +1
result = result + factor*(x**i)
return result
a = [3, 8, 5, 0, 7, 1, 7, 8] # 自行输入的系数列表
time_begin_1 = time.time()
print(func_1(a, 1)) # 此处x取1
time_end_1 = time.time()
time_1 = time_end_1 - time_begin_1
print("tiem: ", time_1)
至此,代码分享完毕,如果有其他实现方式,欢迎交流讨论。