python高斯求和_二、算法分析

一、什么是算法分析

程序和算法的區別:

算法是對問題解決的分步描述

程序是采用某種編程語言實現的算法,同一個算法通過不同的程序員采用不同的編程語言,能產生很多程序

算法分析的概念:

算法分析主要就是從計算資源消耗的角度來評判和比較算法

更高效利用計算資源,或者更少占用計算資源的算法,就是好算法

計算資源指標:

一種是算法解決問題過程中需要的存儲空間或內存

另一種是算法的執行時間

運行時間檢測:

1 #累計求和程序的運行時間檢測

2 #迭代法

3 importtime4

5 defsum1(n):6 start =time.time()7 theSum =08 for i in range(1,n+1):9 theSum +=i10 end =time.time()11 return theSum, end -start12

13 for i in range(5):14 print('Sum is %d required %10.7f seconds'%sum1(10000))

n = 10000 時,執行5次的結果為

Sum is 50005000 required 0.0000000seconds

Sumis 50005000 required 0.0009980seconds

Sumis 50005000 required 0.0000000seconds

Sumis 50005000 required 0.0000000seconds

Sumis 50005000 required 0.0009968 seconds

n = 100000 時, 執行5次的結果為

Sum is 5000050000 required 0.0049877seconds

Sumis 5000050000 required 0.0049853seconds

Sumis 5000050000 required 0.0049860seconds

Sumis 5000050000 required 0.0049872seconds

Sumis 5000050000 required 0.0049863 seconds

n = 1000000時,執行5次的結果為

Sum is 500000500000 required 0.0528579seconds

Sumis 500000500000 required 0.0518231seconds

Sumis 500000500000 required 0.0528951seconds

Sumis 500000500000 required 0.0519009seconds

Sumis 500000500000 required 0.0527823 seconds

1 #累計求和程序的運行時間檢測

2 #利用高斯求和公式的無迭代算法

3 importtime4

5 defsum2(n):6 start =time.time()7 theSum = (n * (n+1)) / 2

8 end =time.time()9 return theSum, end -start10

11 for i in range(5):12 print('Sum is %d required %10.7f seconds'%sum2(10000))

n = 10000,100000,1000000時,執行5次的結果時間均相同,為0.0000000 seconds

比較:

第一種迭代算法包含一個循環,這個循環運行次數跟累加值n有關,n增加,循環次數也會增加

第二種無迭代算法運行時間比第一種短很多,運行時間與累計對象n的大小無關

二、大O表示法

算法時間度量指標:

一個算法所實施的操作數量或步驟數可作為獨立于具體程序/機器的度量指標

賦值語句是度量指標的一個合適選擇,一條賦值語句同時包含了(表達式)計算和(變量)存儲兩個基本資源

數量級函數(Order of Magnitude)

基本操作數量函數T(n)的精確值不是特別重要,重要的是T(n)中起決定性因素的主導部分

數量級函數描述了T(n)中隨著n增加而增加速度最快的主導部分

d990d0d2709207bdf2593bbfacd6f8d6.png

常見的大O數量級函數:

8c0f975ca89d8c13a35c06801d46e5cd.png

5a1abe4fbd87123b34af9635703c897b.png

86706c012190dad69670e95fc0726815.png

三、"變位詞"判斷問題

9007901b1ccfb79f9e23a31e9b05c3c0.png

22b72cf922f943647b2d98ef0d9c6dc7.png

5ec374be2595952cf2dfb1a7ef23b654.png

1 #解法1:逐字檢查

2

3 defanagramSolution1(s1, s2):4 alist =list(s2)5 pos1 =06 stillOK =True7 while pos1 < len(s1) andstillOK:8 pos2 =09 found =False10 while pos2 < len(alist) and notfound:11 if s1[pos1] ==s2[pos2]:12 found =True13 else:14 pos2 = pos2 + 1

15 iffound:16 alist[pos2] =None17 else:18 stillOK =False19 pos1 = pos1 + 1

20 returnstillOK21

22 print(anagramSolution1('abcd','cabd'))

c9c8e8c182bc01a1c6829724491968ff.png

68f724bad5a33d9a9f6bd2ca7369ecb7.png

24ffbdb08452179e1accf77abf129c75.png

1 #解法2:排序比較

2

3 defanagramSolution2(s1, s2):4 alist1 =list(s1)5 alist2 =list(s2)6

7 alist1.sort()8 alist2.sort()9 pos =010 matches =True11 while pos < len(s1) andmatches:12 if alist1[pos] ==alist2[pos]:13 pos = pos + 1

14 else:15 matches =False16 returnmatches17

18 print(anagramSolution2('abcde','edcba'))

d3d25b88f5579714a5041adc87811627.png

335ad28bd0019809bdcb33d538feff37.png

1 #解法4:計數比較

2

3 defanagramSolution4(s1, s2):4 c1 = [0] * 26

5 c2 = [0] * 26

6 for i ins1:7 pos = ord(i) - ord('a')8 c1[pos] = c1[pos] + 1

9 for j ins2:10 pos = ord(j) - ord('a')11 c2[pos] = c2[pos] + 1

12 k =013 stillOK =True14 while k < 26 andstillOK:15 if c1[k] ==c2[k]:16 k = k + 1

17 else:18 stillOK =False19 returnstillOK20

21 print(anagramSolution4('abcde','edcba'))

d1827162e8ca682004875b3da5c75c31.png

4050aed6a60eac7240b9b38d532260ec.png

四、Python數據類型的性能

1、列表list和字典dict的對比:

4f9d3082e5efeaddbf11ed17c48df7be.png

2、4種生成前n個整數列表的方法性能比較

1 #4種生成前n個整數列表的方法性能比較

2 from timeit importTimer3

4 deftest1():5 l =[]6 for i in range(1000):7 l = l +[i]8

9 deftest2():10 l =[]11 for i in range(1000):12 l.append(i)13

14 deftest3():15 l = [i for i in range(1000)]16

17 deftest4():18 l = list(range(1000))19

20 t1 = Timer('test1()','from __main__ import test1') #創建一個Timer對象,指定需要反復運行的語句和只需要運行一次的“安裝語句”

21 print('concat %f seconds\n' % t1.timeit(number=10000)) #調用Timer對象的timeit方法,其中可以指定反復運行多少次

22

23 t2 = Timer('test2()','from __main__ import test2')24 print('append %f seconds\n' % t2.timeit(number=10000))25 t3 = Timer('test3()','from __main__ import test3')26 print('comprehension %f seconds\n' % t3.timeit(number=10000))27 t4 = Timer('test4()','from __main__ import test4')28 print('list range %f seconds\n' % t4.timeit(number=10000))

concat 14.517047seconds

append0.859504seconds

comprehension0.517713seconds

list range0.127913 seconds

3、list.pop的計時試驗

17a026d286879ef067552fb8f298952a.png

#-*- coding: utf-8 -*-

"""Created on Thu Oct 17 20:30:27 2019

@author: wu"""

#list.pop的計時試驗,比較pop()和pop(0)兩種方法

from timeit importTimerimporttimeitimportnumpy as npimportmatplotlib.pyplot as plt

pop0= timeit.Timer('x.pop(0)','from __main__ import x')

popend= timeit.Timer('x.pop()','from __main__ import x')print('pop(0) pop()')

l1=[]

l2=[]for i in range(1000000,10000001,100000):

x=list(range(i))

pt= popend.timeit(number=100)

l1.append(pt)

x=list(range(i))

pz= pop0.timeit(number=100)

l2.append(pz)print('%15.5f,%15.5f' %(pz,pt))

j= np.arange(1000000,10000001,100000)

plt.plot(j,l1,label='pop')

plt.plot(j,l2,label='pop0')

plt.xlabel('n')

plt.ylabel('time(s)')

plt.legend()

plt.show()

f32aab8ef841f9eba33d780ab7dae5d5.png

4、list和dict的in操作對比

1 #驗證list中檢索一個值,以及dict中檢索一個值的對比

2 importtimeit3 importrandom4 importnumpy as np5 importmatplotlib.pyplot as plt6

7 l1,l2 =[],[]8 n =[]9 for i in range(10000,1000001,20000):10 t = timeit.Timer('random.randrange(%d) in x'%i,'from __main__ import random,x')11 x =list(range(i))12 lst_time = t.timeit(number=100)13 l1.append(lst_time)14 x = {j:None for j inrange(i)}15 d_time = t.timeit(number=100)16 l2.append(d_time)17 print('{},{:10.3f},{:10.3f}'.format(i,lst_time,d_time))18

19 for i in range(10000,1000001,20000):20 n.append(i)21

22 plt.plot(n,l1,'go-',label='list')23 plt.plot(n,l2,'r*-',label='dict')24 plt.xlabel('n')25 plt.ylabel('time')26 plt.legend()27 plt.show()28

25853e85684919e1d73796dc21adf339.png

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/271932.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/271932.shtml
英文地址,請注明出處:http://en.pswp.cn/news/271932.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

硬件:交換機基礎知識

1、交換機的概念交換機&#xff08;Switch&#xff09;意為“開關”&#xff0c;是一種用于電&#xff08;光&#xff09;信號轉發的網絡設備。它可以為接入交換機的任意兩個網絡節點提供獨享的電信號通路。最常見的交換機是以太網交換機。其他常見的還有電話語音交換機、光纖交…

PhantomJS 與python的結合

待完善 一.簡介 PhantomJS是一個基于webkit的JavaScript API。它使用QtWebKit作為它核心瀏覽器的功能&#xff0c;使用webkit來編譯解釋執行JavaScript代碼。任何你可以在基于webkit瀏覽器 做的事情&#xff0c;它都能做到。它不僅是個隱形的瀏覽器&#xff0c;提供了諸如CSS選…

mysql對數據庫的操作_MySQL數據庫對數據庫的操作

1.創建數據庫mysqlgt; create database if not exists tongcheng; Query OK, 1 row affected (0.01 sec) mysqlgt; 2.查看創建數1.創建數據庫mysql> create database if not exists tongcheng;Query OK, 1 row affected (0.01 sec)mysql>2.查看創建數據庫時的選項mysql&g…

static用途

static關鍵字的用途 一句話描述就是&#xff1a;方便在沒有創建對象的情況下進行調用(方法/變量)。 顯然&#xff0c;被static關鍵字修飾的方法或者變量不需要依賴于對象來進行訪問&#xff0c;只要類被加載了&#xff0c;就可以通過類名去進行訪問。 static可以用來修飾類的…

硬件:寬帶貓(光貓)的基礎知識

??作者主頁&#xff1a;IT技術分享社區 ??作者簡介&#xff1a;大家好,我是IT技術分享社區的博主&#xff0c;從事C#、Java開發九年&#xff0c;對數據庫、C#、Java、前端、運維、電腦技巧等經驗豐富。 ??個人榮譽&#xff1a; 數據庫領域優質創作者&#x1f3c6;&#x…

篩法求素數

一般&#xff1a; #include<stdio.h> int main() { int a[100], i, j; for(i 2; i < 100; i) a[i] 1;//令2-99都為1 for(i 2; i < 100/2; i)//2 - 到 范圍的一半的所有倍數 { if(a[i] 1)//還未被篩 素數不會被篩 合數會被篩 …

mysql實用管理器添加外鍵_MySQL 添加外鍵

MySQL 添加外鍵MySQL 添加外鍵DROP TABLE IF EXISTS nation;CREATE TABLE nation(pii_Nation smallint(2) unsigned NOT NULL default 0,pii_NatinoName varchar(40) NOT NULL default ,PRIMARY KEY (pii_Nation))ENGINEInnoDB DEFAULT CHARSETutf8;DROP TABLE IF EXISTS user…

Sentinel介紹和Windows下安裝Sentinel-dashboard

Sentinel 是什么&#xff1f; 隨著微服務的流行&#xff0c;服務和服務之間的穩定性變得越來越重要。Sentinel 以流量為切入點&#xff0c;從流量控制、熔斷降級、系統負載保護等多個維度保護服務的穩定性。 Sentinel 具有以下特征: 豐富的應用場景&#xff1a;Sentinel 承接…

盤點物聯網常用的八種通信協議

目錄 1、藍牙 2、Zigbee 3、6LoWPAN 4、Wi-Fi 6、ModBus 7、PROFINET 8、EtherCAT 1、藍牙 兼容的藍牙IoT傳感器非常適合需要短距離連接和低功率通信的應用。藍牙協議的有效范圍為50到100米&#xff0c;支持高達1 Mbps的數據傳輸速率。 最近&#xff0c;物聯網開發人員已經表現…

java 發郵件_java實現郵件的發送

文章所用jar文件鏈接&#xff1a;https://pan.baidu.com/s/1YaxhdkaCTC4TUDL-y9-ASQ提取碼&#xff1a;30ow程序入口&#xff0c;發送工具類package test;import org.apache.commons.mail.EmailException;/*** 郵箱發送工具類* author Administrator**/public class EmailUtil …

軟件工程與程序算法

軟件工程包括需求分析、概要設計、詳細設計、代碼實現和維護五個部分。而具體的程序編碼只占其中的一小部分。算法是在代碼設計中的基礎&#xff0c;提供了解決問題的方法。軟件工程是應用計算機科學、數學及管理科學等原理&#xff0c;開發軟件的工程。軟件工程借鑒傳統工程的…

docker安裝Sentinel

1:拉取鏡像&#xff1a;docker pull bladex/sentinel-dashboard 2:啟動 docker run --name sentinel -d -p 8858:8858 -d bladex/sentinel-dashboard 3&#xff1a;訪問 http://公網ip:8858 4&#xff1a;登錄,用戶名和密碼都是sentinel

藍牙技術的工作原理及用途

所謂藍牙技術就是一種全球無線通訊標準&#xff0c;在一定距離內連接設備。目前&#xff0c;藍牙技術也已應用到各個領域中&#xff0c;并已成為接入物聯網&#xff08;IOT&#xff09;的主要技術。那關于藍牙技術的工作原理本文將進行介紹&#xff0c;并概括其特點。藍牙技術的…

什么是BusyBox?

BusyBox 是標準 Linux 工具的一個單個可執行實現。BusyBox 包含了一些簡單的工具&#xff0c;例如 cat 和 echo&#xff0c;還包含了一些更大、更復雜的工具&#xff0c;例如 grep、find、mount 以及 telnet。有些人將 BusyBox 稱為 Linux 工具里的瑞士軍刀.簡單的說BusyBox就好…

iOS十進制切割格式轉換

//"123456789" 轉換后 "123,456,789" interface NSString (num)- (NSString *)money;endimplementation NSString (num)- (NSString *)money{NSNumberFormatter *numFormat [[NSNumberFormatter alloc] init];[numFormat setNumberStyle:NSNumberFormatte…

同一接口有多個實現類,怎么來注入一個指定的實現?@Resource、@Autowired、@Qualifier

如果一個接口有2個以上不同的實現類, 那么如何Autowire一個指定的實現 1:首先,UserService接口有兩個實現類 UserService1和 UserService2 UserService接口 2:以下是UserService接口的兩個實現類UserService1和UserService2&#xff0c;請注意service注解的使用方式&#xff…

java類型比較_java 基本數據類型 ==和equals()比較

1.基本類型的存儲Java 8種基本類型都是存儲在堆棧中&#xff0c;例&#xff1a;int i 1;String str "hello world";也是存儲在堆棧中。new基本類型的包裝器類型和new String()都是存儲在堆內存中。例Integer i new Integer(1);String str new String("hello…

嵌入式操作系統的主要特點都有哪些

嵌入式操作系統&#xff08;EOS&#xff09;是指用于嵌入式系統的操作系統。嵌入式操作系統是一種用途廣泛的系統軟件&#xff0c;通常包括與硬件的底層驅動軟件、系統內核、設備驅動接口、通信協議、圖形界面、標準化瀏覽器等。嵌入式系統分為4層&#xff1a;硬件層、驅動層、…

UIWebView UITextView

// // ViewController.m // 網頁 //#import "ViewController.h"interface ViewController ()<UITextFieldDelegate,UIWebViewDelegate> property (weak, nonatomic) IBOutlet UITextField *textFiled; property (weak, nonatomic) IBOutlet UIWebView *webVi…

BeanFactory和ApplicationContext有什么區別?

BeanFactory&#xff1a; 是Spring里面最底層的接口&#xff0c;提供了最簡單的容器的功能&#xff0c;只提供了實例化對象和拿對象的功能 ApplicationContext&#xff1a; 應用上下文&#xff0c;繼承BeanFactory接口&#xff0c;它是Spring的一各更高級的容器&#xff0c;提…