【Python】(一)Python学习基础

作者: hitsunbo | 来源:发表于2017-02-17 15:12 被阅读68次

Python 是一门现代化的面相对象的编程语言,有着丰富的扩展库,并具有易于学习、应用广泛的特点。

对于python程序执行效率的分析,时间复杂度与空间复杂度同样是适用的。在总体时间复杂度相同的情况下,我们也可以直观的使用同一台机器上的运行时间来做直接比较。在 python的time 模块中有一个 time 函数,它可以在任意被调用的地方返回系统时钟的当前时间(以秒为单位)。通过在开始和结束的时候分别调用两次 time 函数,然后计算差值,就可以得到一个函数执行的精确秒数。

以从1到N的自然数求和为例子

import time

def Sum_1(N):
    sum = 0
    for i in range(1,N+1):
        sum += i
    return sum
    
def main():
    N = 100000
    for echo in range(5):
        begin_time = time.time()
        sum1 = Sum_1(N)
        end_time = time.time()
        print("Sum method 1 -- Echo %d -- Result %d -- Cost %f seconds."%(echo, sum1, end_time-begin_time))

if __name__ == "__main__":
    main()

运行结果为:

Sum method 1 -- Echo 0 -- Result 5000050000 -- Cost 0.036053 seconds.
Sum method 1 -- Echo 1 -- Result 5000050000 -- Cost 0.032034 seconds.
Sum method 1 -- Echo 2 -- Result 5000050000 -- Cost 0.018009 seconds.
Sum method 1 -- Echo 3 -- Result 5000050000 -- Cost 0.010006 seconds.
Sum method 1 -- Echo 4 -- Result 5000050000 -- Cost 0.010509 seconds.

可以看出,Python每次运行都能得出正确的结果,而运行时间也在同一个数量级上波动。
如果我们采用高斯求和公式进行算法改进——


高斯求和公式
import time

def Sum_1(N):
    sum = 0
    for i in range(1,N+1):
        sum += i
    return sum

def Sum_2(N):
    sum = (1+N)*N/2
    return sum
    
def main():
    N = 10000000
    ###累加求和
    for echo in range(5):
        begin_time = time.time()
        sum1 = Sum_1(N)
        end_time = time.time()
        print("Sum method 1 -- Echo %d -- Result %d -- Cost %f seconds."%(echo, sum1, end_time-begin_time))
    
    print("----------------------------------------------")
    
    ###使用高斯公式
    for echo in range(5):
        begin_time = time.time()
        sum1 = Sum_2(N)
        end_time = time.time()
        print("Sum method 2 -- Echo %d -- Result %d -- Cost %f seconds."%(echo, sum1, end_time-begin_time))

if __name__ == "__main__":
    main()

运行结果如下:

Sum method 1 -- Echo 0 -- Result 50000005000000 -- Cost 1.237429 seconds.
Sum method 1 -- Echo 1 -- Result 50000005000000 -- Cost 1.181615 seconds.
Sum method 1 -- Echo 2 -- Result 50000005000000 -- Cost 1.044307 seconds.
Sum method 1 -- Echo 3 -- Result 50000005000000 -- Cost 1.056946 seconds.
Sum method 1 -- Echo 4 -- Result 50000005000000 -- Cost 1.041368 seconds.
----------------------------------------------
Sum method 2 -- Echo 0 -- Result 50000005000000 -- Cost 0.000000 seconds.
Sum method 2 -- Echo 1 -- Result 50000005000000 -- Cost 0.000998 seconds.
Sum method 2 -- Echo 2 -- Result 50000005000000 -- Cost 0.000000 seconds.
Sum method 2 -- Echo 3 -- Result 50000005000000 -- Cost 0.000000 seconds.
Sum method 2 -- Echo 4 -- Result 50000005000000 -- Cost 0.000000 seconds.

可以看出,高斯公式对于大数累加求和更为有利,这是符合常识的。
从以上的例子里我们也能感受到,python对于大数不需要做单独的处理,这也是python广泛应用于科学计算的原因之一。

相关文章

网友评论

    本文标题:【Python】(一)Python学习基础

    本文链接:https://www.haomeiwen.com/subject/pszkwttx.html