Python3 實例


一直以來,總想寫些什么,但不知從何處落筆。

今兒個倉促,也不知道怎么寫,就把手里練習過的例子,整理了一下。

希望對初學者有用,都是非常基礎的例子,很適合初練。

好了,Follow me。 

一、Python Hello World 實例

以下實例為學習Python的第一個實例,即如何輸出"Hello World!":

1 # -*- coding: UTF-8 -*-
2 
3 # Filename : helloworld.py
4 # author by : www.runoob.com
5 
6 # 該實例輸出 Hello World!
7 print('Hello World')
View Code 

二、Python 數字求和

以下實例為通過用戶輸入兩個數字,並計算兩個數字之和:

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # 用戶輸入數字
 7 num1 = input('輸入第一個數字:')
 8 num2 = input('輸入第二個數字:')
 9  
10 # 求和
11 sum = float(num1) + float(num2)
12  
13 # 顯示計算結果
14 print('數字 {0} 和 {1} 相加結果為: {2}'.format(num1, num2, sum))
View Code

說明:使用了內置函數 input() 來獲取用戶的輸入,input() 返回一個字符串,所以我們需要使用 float() 方法將字符串轉換為數字。

另外,我們還可以將以上運算,合並為一行代碼:

1 # -*- coding: UTF-8 -*-
2  
3 # Filename : test.py
4 # author by : www.runoob.com
5  
6 print('兩數之和為 %.1f' %(float(input('輸入第一個數字:'))+float(input('輸入第二個數字:'))))
View Code 

三、Python 平方根

1 # -*- coding: UTF-8 -*-
2  
3 # Filename : test.py
4 # author by : www.runoob.com
5  
6 num = float(input('請輸入一個數字: '))
7 num_sqrt = num ** 0.5
8 print(' %0.3f 的平方根為 %0.3f'%(num ,num_sqrt))
View Code

說明:指數運算符 ** 來計算該數的平方根

該程序只適用於正數。負數和復數可以使用以下的方式:

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # 計算實數和復數平方根
 7 # 導入復數數學模塊
 8  
 9 import cmath
10  
11 num = int(input("請輸入一個數字: "))
12 num_sqrt = cmath.sqrt(num)
13 print('{0} 的平方根為 {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))
View Code

該實例中,我們使用了 cmath (complex math) 模塊的 sqrt() 方法。

四、Python 二次方程

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # 二次方程式 ax**2 + bx + c = 0
 5 # a、b、c 用戶提供,為實數,a ≠ 0
 6  
 7 # 導入 cmath(復雜數學運算) 模塊
 8 import cmath
 9  
10 a = float(input('輸入 a: '))
11 b = float(input('輸入 b: '))
12 c = float(input('輸入 c: '))
13  
14 # 計算
15 d = (b**2) - (4*a*c)
16  
17 # 兩種求解方式
18 sol1 = (-b-cmath.sqrt(d))/(2*a)
19 sol2 = (-b+cmath.sqrt(d))/(2*a)
20  
21 print('結果為 {0} 和 {1}'.format(sol1,sol2))
View Code

該實例中,我們使用了 cmath (complex math) 模塊的 sqrt() 方法 來計算平方根。

五、Python 計算三角形的面積

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6  
 7 a = float(input('輸入三角形第一邊長: '))
 8 b = float(input('輸入三角形第二邊長: '))
 9 c = float(input('輸入三角形第三邊長: '))
10  
11 # 計算半周長
12 s = (a + b + c) / 2
13  
14 # 計算面積
15 area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
16 print('三角形面積為 %0.2f' %area)
View Code

六、Python 計算圓的面積

1 # 定義一個方法來計算圓的面積
2 def findArea(r): 
3     PI = 3.142
4     return PI * (r*r)
5   
6 # 調用方法
7 print("圓的面積為 %.6f" % findArea(5)) 
View Code 

七、Python 隨機數生成

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # 生成 0 ~ 9 之間的隨機數
 7  
 8 # 導入 random(隨機數) 模塊
 9 import random
10  
11 print(random.randint(0,9))
View Code

以上實例我們使用了 random 模塊的 randint() 函數來生成隨機數。

八、Python 攝氏溫度轉華氏溫度

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # 用戶輸入攝氏溫度
 7  
 8 # 接收用戶輸入
 9 celsius = float(input('輸入攝氏溫度: '))
10  
11 # 計算華氏溫度
12 fahrenheit = (celsius * 1.8) + 32
13 print('%0.1f 攝氏溫度轉為華氏溫度為 %0.1f ' %(celsius,fahrenheit))
View Code

九、Python 交換變量

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # 用戶輸入
 7  
 8 x = input('輸入 x 值: ')
 9 y = input('輸入 y 值: ')
10  
11 # 創建臨時變量,並交換
12 temp = x
13 x = y
14 y = temp
15  
16 print('交換后 x 的值為: {}'.format(x))
17 print('交換后 y 的值為: {}'.format(y))
View Code

以上實例中,我們創建了臨時變量 temp ,並將 x 的值存儲在 temp 變量中,接着將 y 值賦給 x,最后將 temp 賦值給 y 變量。

不使用臨時變量  

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # 用戶輸入
 7  
 8 x = input('輸入 x 值: ')
 9 y = input('輸入 y 值: ')
10  
11 # 不使用臨時變量
12 x,y = y,x
13  
14 print('交換后 x 的值為: {}'.format(x))
15 print('交換后 y 的值為: {}'.format(y))
View Code

十、Python if 語句

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # 用戶輸入數字
 5  
 6 num = float(input("輸入一個數字: "))
 7 if num > 0:
 8    print("正數")
 9 elif num == 0:
10    print("")
11 else:
12    print("負數")
View Code

我們也可以使用內嵌 if 語句來實現:

 1 # Filename :test.py
 2 # author by : www.runoob.com
 3  
 4 # 內嵌 if 語句
 5  
 6 num = float(input("輸入一個數字: "))
 7 if num >= 0:
 8    if num == 0:
 9        print("")
10    else:
11        print("正數")
12 else:
13    print("負數")
View Code

 

優化增加輸入字符的判斷以及異常輸出:

 1 while True:
 2     try:
 3         num=float(input('請輸入一個數字:'))
 4         if num==0:
 5             print('輸入的數字是零')
 6         elif num>0:
 7             print('輸入的數字是正數')
 8         else:
 9             print('輸入的數字是負數')
10         break
11     except ValueError:
12         print('輸入無效,需要輸入一個數字')
View Code

十一、Python 判斷字符串是否為數字

以下實例通過創建自定義函數 is_number() 方法來判斷字符串是否為數字:

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 def is_number(s):
 7     try:
 8         float(s)
 9         return True
10     except ValueError:
11         pass
12  
13     try:
14         import unicodedata
15         unicodedata.numeric(s)
16         return True
17     except (TypeError, ValueError):
18         pass
19  
20     return False
21  
22 # 測試字符串和數字
23 print(is_number('foo'))   # False
24 print(is_number('1'))     # True
25 print(is_number('1.3'))   # True
26 print(is_number('-1.37')) # True
27 print(is_number('1e3'))   # True
28  
29 # 測試 Unicode
30 # 阿拉伯語 5
31 print(is_number('٥'))  # True
32 # 泰語 2
33 print(is_number(''))  # True
34 # 中文數字
35 print(is_number('')) # True
36 # 版權號
37 print(is_number('©'))  # False
View Code

更多方法

Python isdigit() 方法檢測字符串是否只由數字組成。

Python isnumeric() 方法檢測字符串是否只由數字組成。這種方法是只針對unicode對象。

十二、Python 判斷奇數偶數

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # Python 判斷奇數偶數
 5 # 如果是偶數除於 2 余數為 0
 6 # 如果余數為 1 則為奇數
 7  
 8 num = int(input("輸入一個數字: "))
 9 if (num % 2) == 0:
10    print("{0} 是偶數".format(num))
11 else:
12    print("{0} 是奇數".format(num))
View Code

十三、Python 判斷閏年

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 year = int(input("輸入一個年份: "))
 7 if (year % 4) == 0:
 8    if (year % 100) == 0:
 9        if (year % 400) == 0:
10            print("{0} 是閏年".format(year))   # 整百年能被400整除的是閏年
11        else:
12            print("{0} 不是閏年".format(year))
13    else:
14        print("{0} 是閏年".format(year))       # 非整百年能被4整除的為閏年
15 else:
16    print("{0} 不是閏年".format(year))
View Code
1 import calendar
2 
3 year = int(input("請輸入年份:"))
4 check_year=calendar.isleap(year)
5 if check_year == True:
6     print ("閏年")
7 else:
8     print ("平年")
View Code

十四、Python 獲取最大值函數

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # 最簡單的
 7 print(max(1, 2))
 8 print(max('a', 'b'))
 9  
10 # 也可以對列表和元組使用
11 print(max([1,2]))
12 print(max((1,2)))
13  
14 # 更多實例
15 print("80, 100, 1000 最大值為: ", max(80, 100, 1000))
16 print("-20, 100, 400最大值為: ", max(-20, 100, 400))
17 print("-80, -20, -10最大值為: ", max(-80, -20, -10))
18 print("0, 100, -400最大值為:", max(0, 100, -400))
View Code

十五、Python 質數判斷

一個大於1的自然數,除了1和它本身外,不能被其他自然數(質數)整除(2, 3, 5, 7等),換句話說就是該數除了1和它本身以外不再有其他的因數。

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # Python 程序用於檢測用戶輸入的數字是否為質數
 7  
 8 # 用戶輸入數字
 9 num = int(input("請輸入一個數字: "))
10  
11 # 質數大於 1
12 if num > 1:
13    # 查看因子
14    for i in range(2,num):
15        if (num % i) == 0:
16            print(num,"不是質數")
17            print(i,"乘於",num//i,"",num)
18            break
19    else:
20        print(num,"是質數")
21        
22 # 如果輸入的數字小於或等於 1,不是質數
23 else:
24    print(num,"不是質數")
View Code

十六、Python 輸出指定范圍內的素數 

素數(prime number)又稱質數,有無限個。除了1和它本身以外不再被其他的除數整除。

 1 #!/usr/bin/python3
 2  
 3 # 輸出指定范圍內的素數
 4  
 5 # take input from the user
 6 lower = int(input("輸入區間最小值: "))
 7 upper = int(input("輸入區間最大值: "))
 8  
 9 for num in range(lower,upper + 1):
10     # 素數大於 1
11     if num > 1:
12         for i in range(2,num):
13             if (num % i) == 0:
14                 break
15         else:
16             print(num)
View Code

十七、Python 階乘實例

整數的階乘(英語:factorial)是所有小於及等於該數的正整數的積,0的階乘為1。即:n!=1×2×3×...×n。

 1 #!/usr/bin/python3
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # 通過用戶輸入數字計算階乘
 7  
 8 # 獲取用戶輸入的數字
 9 num = int(input("請輸入一個數字: "))
10 factorial = 1
11  
12 # 查看數字是負數,0 或 正數
13 if num < 0:
14    print("抱歉,負數沒有階乘")
15 elif num == 0:
16    print("0 的階乘為 1")
17 else:
18    for i in range(1,num + 1):
19        factorial = factorial*i
20    print("%d 的階乘為 %d" %(num,factorial))
View Code

十八、Python 九九乘法表

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # 九九乘法表
 7 for i in range(1, 10):
 8     for j in range(1, i+1):
 9         print('{}x{}={}\t'.format(j, i, i*j), end='')
10     print()
View Code

通過指定end參數的值,可以取消在末尾輸出回車符,實現不換行。

十九、Python 斐波那契數列

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # Python 斐波那契數列實現
 7  
 8 # 獲取用戶輸入數據
 9 nterms = int(input("你需要幾項?"))
10  
11 # 第一和第二項
12 n1 = 0
13 n2 = 1
14 count = 2
15  
16 # 判斷輸入的值是否合法
17 if nterms <= 0:
18    print("請輸入一個正整數。")
19 elif nterms == 1:
20    print("斐波那契數列:")
21    print(n1)
22 else:
23    print("斐波那契數列:")
24    print(n1,",",n2,end=" , ")
25    while count < nterms:
26        nth = n1 + n2
27        print(nth,end=" , ")
28        # 更新值
29        n1 = n2
30        n2 = nth
31        count += 1
View Code

二十、Python 阿姆斯特朗數

如果一個n位正整數等於其各位數字的n次方之和,則稱該數為阿姆斯特朗數。 例如1^3 + 5^3 + 3^3 = 153。

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # Python 檢測用戶輸入的數字是否為阿姆斯特朗數
 5  
 6 # 獲取用戶輸入的數字
 7 num = int(input("請輸入一個數字: "))
 8  
 9 # 初始化變量 sum
10 sum = 0
11 # 指數
12 n = len(str(num))
13  
14 # 檢測
15 temp = num
16 while temp > 0:
17    digit = temp % 10
18    sum += digit ** n
19    temp //= 10
20  
21 # 輸出結果
22 if num == sum:
23    print(num,"是阿姆斯特朗數")
24 else:
25    print(num,"不是阿姆斯特朗數")
View Code

獲取指定期間內的阿姆斯特朗數

 1 # Filename :test.py
 2 # author by : www.runoob.com
 3  
 4 # 獲取用戶輸入數字
 5 lower = int(input("最小值: "))
 6 upper = int(input("最大值: "))
 7  
 8 for num in range(lower,upper + 1):
 9    # 初始化 sum
10    sum = 0
11    # 指數
12    n = len(str(num))
13  
14    # 檢測
15    temp = num
16    while temp > 0:
17        digit = temp % 10
18        sum += digit ** n
19        temp //= 10
20  
21    if num == sum:
22        print(num)
View Code

二十一、Python 十進制轉二進制、八進制、十六進制

 1 # -*- coding: UTF-8 -*-
 2  
 3 # Filename : test.py
 4 # author by : www.runoob.com
 5  
 6 # 獲取用戶輸入十進制數
 7 dec = int(input("輸入數字:"))
 8  
 9 print("十進制數為:", dec)
10 print("轉換為二進制為:", bin(dec))
11 print("轉換為八進制為:", oct(dec))
12 print("轉換為十六進制為:", hex(dec))
View Code

二十二、Python ASCII碼與字符相互轉換

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # 用戶輸入字符
 5 c = input("請輸入一個字符: ")
 6  
 7 # 用戶輸入ASCII碼,並將輸入的數字轉為整型
 8 a = int(input("請輸入一個ASCII碼: "))
 9  
10  
11 print( c + " 的ASCII 碼為", ord(c))
12 print( a , " 對應的字符為", chr(a))
View Code

二十三、Python 最大公約數算法

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # 定義一個函數
 5 def hcf(x, y):
 6    """該函數返回兩個數的最大公約數"""
 7  
 8    # 獲取最小值
 9    if x > y:
10        smaller = y
11    else:
12        smaller = x
13  
14    for i in range(1,smaller + 1):
15        if((x % i == 0) and (y % i == 0)):
16            hcf = i
17  
18    return hcf
19  
20  
21 # 用戶輸入兩個數字
22 num1 = int(input("輸入第一個數字: "))
23 num2 = int(input("輸入第二個數字: "))
24  
25 print( num1,"", num2,"的最大公約數為", hcf(num1, num2))
View Code 

二十四、Python 最小公倍數算法

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # 定義函數
 5 def lcm(x, y):
 6  
 7    #  獲取最大的數
 8    if x > y:
 9        greater = x
10    else:
11        greater = y
12  
13    while(True):
14        if((greater % x == 0) and (greater % y == 0)):
15            lcm = greater
16            break
17        greater += 1
18  
19    return lcm
20  
21  
22 # 獲取用戶輸入
23 num1 = int(input("輸入第一個數字: "))
24 num2 = int(input("輸入第二個數字: "))
25  
26 print( num1,"", num2,"的最小公倍數為", lcm(num1, num2))
View Code

二十五、Python 簡單計算器實現

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # 定義函數
 5 def add(x, y):
 6    """相加"""
 7  
 8    return x + y
 9  
10 def subtract(x, y):
11    """相減"""
12  
13    return x - y
14  
15 def multiply(x, y):
16    """相乘"""
17  
18    return x * y
19  
20 def divide(x, y):
21    """相除"""
22  
23    return x / y
24  
25 # 用戶輸入
26 print("選擇運算:")
27 print("1、相加")
28 print("2、相減")
29 print("3、相乘")
30 print("4、相除")
31  
32 choice = input("輸入你的選擇(1/2/3/4):")
33  
34 num1 = int(input("輸入第一個數字: "))
35 num2 = int(input("輸入第二個數字: "))
36  
37 if choice == '1':
38    print(num1,"+",num2,"=", add(num1,num2))
39  
40 elif choice == '2':
41    print(num1,"-",num2,"=", subtract(num1,num2))
42  
43 elif choice == '3':
44    print(num1,"*",num2,"=", multiply(num1,num2))
45  
46 elif choice == '4':
47    print(num1,"/",num2,"=", divide(num1,num2))
48 else:
49    print("非法輸入")
View Code

二十六、Python 生成日歷

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # 引入日歷模塊
 5 import calendar
 6  
 7 # 輸入指定年月
 8 yy = int(input("輸入年份: "))
 9 mm = int(input("輸入月份: "))
10  
11 # 顯示日歷
12 print(calendar.month(yy,mm))
View Code

二十七、Python 使用遞歸斐波那契數列

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 def recur_fibo(n):
 5    """遞歸函數
 6    輸出斐波那契數列"""
 7    if n <= 1:
 8        return n
 9    else:
10        return(recur_fibo(n-1) + recur_fibo(n-2))
11  
12  
13 # 獲取用戶輸入
14 nterms = int(input("您要輸出幾項? "))
15  
16 # 檢查輸入的數字是否正確
17 if nterms <= 0:
18    print("輸入正數")
19 else:
20    print("斐波那契數列:")
21    for i in range(nterms):
22        print(recur_fibo(i))
View Code

二十八、Python 文件 IO

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # 寫文件
 5 with open("test.txt", "wt") as out_file:
 6     out_file.write("該文本會寫入到文件中\n看到我了吧!")
 7  
 8 # Read a file
 9 with open("test.txt", "rt") as in_file:
10     text = in_file.read()
11  
12 print(text)
View Code

二十九、Python 字符串判斷

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3 
 4 # 測試實例一
 5 print("測試實例一")
 6 str = "runoob.com"
 7 print(str.isalnum()) # 判斷所有字符都是數字或者字母
 8 print(str.isalpha()) # 判斷所有字符都是字母
 9 print(str.isdigit()) # 判斷所有字符都是數字
10 print(str.islower()) # 判斷所有字符都是小寫
11 print(str.isupper()) # 判斷所有字符都是大寫
12 print(str.istitle()) # 判斷所有單詞都是首字母大寫,像標題
13 print(str.isspace()) # 判斷所有字符都是空白字符、\t、\n、\r
14 
15 print("------------------------")
16 
17 # 測試實例二
18 print("測試實例二")
19 str = "runoob"
20 print(str.isalnum()) 
21 print(str.isalpha()) 
22 print(str.isdigit()) 
23 print(str.islower()) 
24 print(str.isupper()) 
25 print(str.istitle()) 
26 print(str.isspace()) 
View Code

三十、Python 字符串大小寫轉換

1 # Filename : test.py
2 # author by : www.runoob.com
3 
4 str = "www.runoob.com"
5 print(str.upper())          # 把所有字符中的小寫字母轉換成大寫字母
6 print(str.lower())          # 把所有字符中的大寫字母轉換成小寫字母
7 print(str.capitalize())     # 把第一個字母轉化為大寫字母,其余小寫
8 print(str.title())          # 把每個單詞的第一個字母轉化為大寫,其余小寫 
View Code

三十一、Python 計算每個月天數

1 #!/usr/bin/python3
2 # author by : www.runoob.com
3  
4 import calendar
5 monthRange = calendar.monthrange(2016,9)
6 print(monthRange)
View Code

三十二、Python 獲取昨天日期

 1 # Filename : test.py
 2 # author by : www.runoob.com
 3  
 4 # 引入 datetime 模塊
 5 import datetime
 6 def getYesterday(): 
 7     today=datetime.date.today() 
 8     oneday=datetime.timedelta(days=1) 
 9     yesterday=today-oneday  
10     return yesterday
11  
12 # 輸出
13 print(getYesterday())
View Code

三十三、Python list 常用操作

1.list 定義

1 >>> li = ["a", "b", "mpilgrim", "z", "example"]
2 >>> li
3 ['a', 'b', 'mpilgrim', 'z', 'example']
4 >>> li[1]         
5 'b'
View Code

2.list 負數索引

 1 >>> li 
 2 ['a', 'b', 'mpilgrim', 'z', 'example']
 3 >>> li[-1] 
 4 'example'
 5 >>> li[-3] 
 6 'mpilgrim'
 7 >>> li 
 8 ['a', 'b', 'mpilgrim', 'z', 'example']
 9 >>> li[1:3]  
10 ['b', 'mpilgrim'] 
11 >>> li[1:-1] 
12 ['b', 'mpilgrim', 'z'] 
13 >>> li[0:3]  
14 ['a', 'b', 'mpilgrim'] 
View Code

3.list 增加元素

 1 >>> li 
 2 ['a', 'b', 'mpilgrim', 'z', 'example']
 3 >>> li.append("new")
 4 >>> li 
 5 ['a', 'b', 'mpilgrim', 'z', 'example', 'new']
 6 >>> li.insert(2, "new")
 7 >>> li 
 8 ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
 9 >>> li.extend(["two", "elements"]) 
10 >>> li 
11 ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
View Code

4.list 搜索 

 1 >>> li 
 2 ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
 3 >>> li.index("example")
 4 5
 5 >>> li.index("new")
 6 2
 7 >>> li.index("c")
 8 Traceback (innermost last):
 9  File "<interactive input>", line 1, in ?
10 ValueError: list.index(x): x not in list
11 >>> "c" in li
12 False
View Code

5.list 刪除元素

 1 >>> li 
 2 ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
 3 >>> li.remove("z")  
 4 >>> li 
 5 ['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']
 6 >>> li.remove("new")    # 刪除首次出現的一個值
 7 >>> li 
 8 ['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']    # 第二個 'new' 未刪除
 9 >>> li.remove("c")     #list 中沒有找到值, Python 會引發一個異常
10 Traceback (innermost last): 
11  File "<interactive input>", line 1, in ? 
12 ValueError: list.remove(x): x not in list
13 >>> li.pop()      # pop 會做兩件事: 刪除 list 的最后一個元素, 然后返回刪除元素的值。
14 'elements'
15 >>> li 
16 ['a', 'b', 'mpilgrim', 'example', 'new', 'two']
View Code

6.list 運算符

 1 >>> li = ['a', 'b', 'mpilgrim']
 2 >>> li = li + ['example', 'new']
 3 >>> li 
 4 ['a', 'b', 'mpilgrim', 'example', 'new']
 5 >>> li += ['two']         
 6 >>> li 
 7 ['a', 'b', 'mpilgrim', 'example', 'new', 'two']
 8 >>> li = [1, 2] * 3
 9 >>> li 
10 [1, 2, 1, 2, 1, 2] 
View Code

7.使用join鏈接list成為字符串

1 >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
2 >>> ["%s=%s" % (k, v) for k, v in params.items()]
3 ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
4 >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])
5 'server=mpilgrim;uid=sa;database=master;pwd=secret'
View Code

join 只能用於元素是字符串的 list; 它不進行任何的類型強制轉換。連接一個存在一個或多個非字符串元素的 list 將引發一個異常。

8.list 分割字符串

1 >>> li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
2 >>> s = ";".join(li)
3 >>> s 
4 'server=mpilgrim;uid=sa;database=master;pwd=secret'
5 >>> s.split(";")   
6 ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
7 >>> s.split(";", 1) 
8 ['server=mpilgrim', 'uid=sa;database=master;pwd=secret']
View Code

split 與 join 正好相反, 它將一個字符串分割成多元素 list。

注意, 分隔符 (";") 被完全去掉了, 它沒有在返回的 list 中的任意元素中出現。

split 接受一個可選的第二個參數, 它是要分割的次數。

9.list 的映射解析

1 >>> li = [1, 9, 8, 4] 
2 >>> [elem*2 for elem in li]    
3 [2, 18, 16, 8] 
4 >>> li
5 [1, 9, 8, 4] 
6 >>> li = [elem*2 for elem in li] 
7 >>> li 
8 [2, 18, 16, 8] 
View Code

10.dictionary 中的解析

 1 >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
 2 >>> params.keys()
 3 dict_keys(['server', 'database', 'uid', 'pwd'])
 4 >>> params.values()
 5 dict_values(['mpilgrim', 'master', 'sa', 'secret'])
 6 >>> params.items()
 7 dict_items([('server', 'mpilgrim'), ('database', 'master'), ('uid', 'sa'), ('pwd', 'secret')])
 8 >>> [k for k, v in params.items()]
 9 ['server', 'database', 'uid', 'pwd']
10 >>> [v for k, v in params.items()]
11 ['mpilgrim', 'master', 'sa', 'secret']
12 >>> ["%s=%s" % (k, v) for k, v in params.items()]
13 ['server=mpilgrim', 'database=master', 'uid=sa', 'pwd=secret']
View Code

11.list 過濾

1 >>> li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
2 >>> [elem for elem in li if len(elem) > 1]
3 ['mpilgrim', 'foo']
4 >>> [elem for elem in li if elem != "b"]
5 ['a', 'mpilgrim', 'foo', 'c', 'd', 'd']
6 >>> [elem for elem in li if li.count(elem) == 1]
7 ['a', 'mpilgrim', 'foo', 'c']
View Code 

三十四、Python 約瑟夫生者死者小游戲

30 個人在一條船上,超載,需要 15 人下船。

於是人們排成一隊,排隊的位置即為他們的編號。

報數,從 1 開始,數到 9 的人下船。

如此循環,直到船上僅剩 15 人為止,問都有哪些編號的人下船了呢?

 1 people={}
 2 for x in range(1,31):
 3     people[x]=1
 4 # print(people)
 5 check=0
 6 i=1
 7 j=0
 8 while i<=31:
 9     if i == 31:
10         i=1
11     elif j == 15:
12         break
13     else:
14         if people[i] == 0:
15             i+=1
16             continue
17         else:
18             check+=1
19             if check == 9:
20                 people[i]=0
21                 check = 0
22                 print("{}號下船了".format(i))
23                 j+=1
24             else:
25                 i+=1
26                 continue
View Code

三十五、Python 實現秒表功能

 1 import time
 2  
 3 print('按下回車開始計時,按下 Ctrl + C 停止計時。')
 4 while True:
 5     try:
 6         input() # 如果是 python 2.x 版本請使用 raw_input() 
 7         starttime = time.time()
 8         print('開始')
 9         while True:
10             print('計時: ', round(time.time() - starttime, 0), '', end="\r")
11             time.sleep(1)
12     except KeyboardInterrupt:
13         print('結束')
14         endtime = time.time()
15         print('總共的時間為:', round(endtime - starttime, 2),'secs')
16         break
View Code

三十六、Python 計算 n 個自然數的立方和

 1 # 定義立方和的函數
 2 def sumOfSeries(n): 
 3     sum = 0
 4     for i in range(1, n+1): 
 5         sum +=i*i*i 
 6           
 7     return sum
 8   
 9    
10 # 調用函數
11 n = 5
12 print(sumOfSeries(n)) 
View Code

三十七、Python 計算數組元素之和

 1 # 定義函數,arr 為數組,n 為數組長度,可作為備用參數,這里沒有用到
 2 def _sum(arr,n): 
 3       
 4     # 使用內置的 sum 函數計算
 5     return(sum(arr)) 
 6   
 7 # 調用函數
 8 arr=[] 
 9 # 數組元素
10 arr = [12, 3, 4, 15] 
11   
12 # 計算數組元素的長度
13 n = len(arr) 
14   
15 ans = _sum(arr,n) 
16   
17 # 輸出結果
18 print ('數組元素之和為',ans) 
View Code

三十八、Python 數組翻轉指定個數的元素

例如:(ar[], d, n) 將長度為 n 的 數組 arr 的前面 d 個元素翻轉到數組尾部。

 1 def leftRotate(arr, d, n): 
 2     for i in range(d): 
 3         leftRotatebyOne(arr, n) 
 4 def leftRotatebyOne(arr, n): 
 5     temp = arr[0] 
 6     for i in range(n-1): 
 7         arr[i] = arr[i+1] 
 8     arr[n-1] = temp 
 9           
10   
11 def printArray(arr,size): 
12     for i in range(size): 
13         print ("%d"% arr[i],end=" ") 
14   
15 
16 arr = [1, 2, 3, 4, 5, 6, 7] 
17 leftRotate(arr, 2, 7) 
18 printArray(arr, 7) 
View Code
 1 def leftRotate(arr, d, n): 
 2     for i in range(gcd(d,n)): 
 3           
 4         temp = arr[i] 
 5         j = i 
 6         while 1: 
 7             k = j + d 
 8             if k >= n: 
 9                 k = k - n 
10             if k == i: 
11                 break
12             arr[j] = arr[k] 
13             j = k 
14         arr[j] = temp 
15 
16 def printArray(arr, size): 
17     for i in range(size): 
18         print ("%d" % arr[i], end=" ") 
19 
20 def gcd(a, b): 
21     if b == 0: 
22         return a; 
23     else: 
24         return gcd(b, a%b) 
25 
26 arr = [1, 2, 3, 4, 5, 6, 7] 
27 leftRotate(arr, 2, 7) 
28 printArray(arr, 7) 
View Code
 1 def rverseArray(arr, start, end): 
 2     while (start < end): 
 3         temp = arr[start] 
 4         arr[start] = arr[end] 
 5         arr[end] = temp 
 6         start += 1
 7         end = end-1
 8   
 9 def leftRotate(arr, d): 
10     n = len(arr) 
11     rverseArray(arr, 0, d-1) 
12     rverseArray(arr, d, n-1) 
13     rverseArray(arr, 0, n-1) 
14   
15 def printArray(arr): 
16     for i in range(0, len(arr)): 
17         print (arr[i], end=' ') 
18   
19 arr = [1, 2, 3, 4, 5, 6, 7] 
20 leftRotate(arr, 2) 
21 printArray(arr) 
View Code

三十九、Python 將列表中的頭尾兩個元素對調

 1 def swapList(newList): 
 2     size = len(newList) 
 3       
 4     temp = newList[0] 
 5     newList[0] = newList[size - 1] 
 6     newList[size - 1] = temp 
 7       
 8     return newList 
 9 
10 newList = [1, 2, 3] 
11   
12 print(swapList(newList))
View Code
1 def swapList(newList): 
2       
3     newList[0], newList[-1] = newList[-1], newList[0] 
4   
5     return newList 
6       
7 newList = [1, 2, 3] 
8 print(swapList(newList)) 
View Code
 1 def swapList(list): 
 2       
 3     get = list[-1], list[0] 
 4       
 5     list[0], list[-1] = get 
 6       
 7     return list
 8       
 9 newList = [1, 2, 3] 
10 print(swapList(newList)) 
View Code

四十、Python 將列表中的指定位置的兩個元素對調

1 def swapPositions(list, pos1, pos2): 
2       
3     list[pos1], list[pos2] = list[pos2], list[pos1] 
4     return list
5   
6 List = [23, 65, 19, 90] 
7 pos1, pos2  = 1, 3
8   
9 print(swapPositions(List, pos1-1, pos2-1)) 
View Code
 1 def swapPositions(list, pos1, pos2): 
 2       
 3     first_ele = list.pop(pos1)    
 4     second_ele = list.pop(pos2-1) 
 5      
 6     list.insert(pos1, second_ele)   
 7     list.insert(pos2, first_ele)   
 8       
 9     return list
10   
11 List = [23, 65, 19, 90] 
12 pos1, pos2  = 1, 3
13   
14 print(swapPositions(List, pos1-1, pos2-1)) 
View Code
 1 def swapPositions(list, pos1, pos2): 
 2   
 3     get = list[pos1], list[pos2] 
 4        
 5     list[pos2], list[pos1] = get 
 6        
 7     return list
 8   
 9 List = [23, 65, 19, 90] 
10   
11 pos1, pos2  = 1, 3
12 print(swapPositions(List, pos1-1, pos2-1)) 
View Code 

四十一、Python 翻轉列表

1 def Reverse(lst): 
2     return [ele for ele in reversed(lst)] 
3       
4 lst = [10, 11, 12, 13, 14, 15] 
5 print(Reverse(lst)) 
View Code
1 def Reverse(lst): 
2     lst.reverse() 
3     return lst 
4       
5 lst = [10, 11, 12, 13, 14, 15] 
6 print(Reverse(lst)) 
View Code
1 def Reverse(lst): 
2     new_lst = lst[::-1] 
3     return new_lst 
4       
5 lst = [10, 11, 12, 13, 14, 15] 
6 print(Reverse(lst)) 
View Code

四十二、Python 判斷元素是否在列表中存在

 1 test_list = [ 1, 6, 3, 5, 3, 4 ] 
 2   
 3 print("查看 4 是否在列表中 ( 使用循環 ) : ") 
 4   
 5 for i in test_list: 
 6     if(i == 4) : 
 7         print ("存在") 
 8   
 9 print("查看 4 是否在列表中 ( 使用 in 關鍵字 ) : ") 
10 
11 if (4 in test_list): 
12     print ("存在") 
View Code
 1 from bisect import bisect_left  
 2   
 3 # 初始化列表
 4 test_list_set = [ 1, 6, 3, 5, 3, 4 ] 
 5 test_list_bisect = [ 1, 6, 3, 5, 3, 4 ] 
 6   
 7 print("查看 4 是否在列表中 ( 使用 set() + in) : ") 
 8   
 9 test_list_set = set(test_list_set) 
10 if 4 in test_list_set : 
11     print ("存在") 
12   
13 print("查看 4 是否在列表中 ( 使用 sort() + bisect_left() ) : ") 
14   
15 test_list_bisect.sort() 
16 if bisect_left(test_list_bisect, 4): 
17     print ("存在") 
View Code

四十三、Python 清空列表

1 RUNOOB = [6, 0, 4, 1] 
2 print('清空前:', RUNOOB)  
3   
4 RUNOOB.clear()
5 print('清空后:', RUNOOB)  
View Code

四十四、Python 復制列表

1 def clone_runoob(li1): 
2     li_copy = li1[:] 
3     return li_copy 
4   
5 li1 = [4, 8, 2, 10, 15, 18] 
6 li2 = clone_runoob(li1) 
7 print("原始列表:", li1) 
8 print("復制后列表:", li2) 
View Code
1 def clone_runoob(li1): 
2     li_copy = [] 
3     li_copy.extend(li1) 
4     return li_copy 
5   
6 li1 = [4, 8, 2, 10, 15, 18] 
7 li2 = clone_runoob(li1) 
8 print("原始列表:", li1) 
9 print("復制后列表:", li2) 
View Code
1 def clone_runoob(li1): 
2     li_copy = list(li1) 
3     return li_copy 
4   
5 li1 = [4, 8, 2, 10, 15, 18] 
6 li2 = clone_runoob(li1) 
7 print("原始列表:", li1) 
8 print("復制后列表:", li2) 
View Code

四十五、Python 計算元素在列表中出現的次數

 1 def countX(lst, x): 
 2     count = 0
 3     for ele in lst: 
 4         if (ele == x): 
 5             count = count + 1
 6     return count 
 7   
 8 lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] 
 9 x = 8
10 print(countX(lst, x)) 
View Code
1 def countX(lst, x): 
2     return lst.count(x) 
3   
4 lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] 
5 x = 8
6 print(countX(lst, x)) 
View Code

四十六、Python 計算列表元素之和

1 total = 0
2   
3 list1 = [11, 5, 17, 18, 23]  
4   
5 for ele in range(0, len(list1)): 
6     total = total + list1[ele] 
7   
8 print("列表元素之和為: ", total) 
View Code
 1 total = 0
 2 ele = 0
 3   
 4 list1 = [11, 5, 17, 18, 23]  
 5   
 6 while(ele < len(list1)): 
 7     total = total + list1[ele] 
 8     ele += 1
 9       
10 print("列表元素之和為: ", total) 
View Code
 1 list1 = [11, 5, 17, 18, 23] 
 2 
 3 def sumOfList(list, size): 
 4    if (size == 0): 
 5      return 0
 6    else: 
 7      return list[size - 1] + sumOfList(list, size - 1) 
 8       
 9 total = sumOfList(list1, len(list1)) 
10 
11 print("列表元素之和為: ", total) 
View Code

四十七、Python 計算列表元素之積

 1 def multiplyList(myList) : 
 2       
 3     result = 1
 4     for x in myList: 
 5          result = result * x  
 6     return result  
 7       
 8 list1 = [1, 2, 3]  
 9 list2 = [3, 2, 4] 
10 print(multiplyList(list1)) 
11 print(multiplyList(list2)) 
View Code

四十八、Python 查找列表中最小元素

1 list1 = [10, 20, 4, 45, 99] 
2   
3 list1.sort() 
4   
5 print("最小元素為:", *list1[:1]) 
View Code
1 list1 = [10, 20, 1, 45, 99] 
2   
3 print("最小元素為:", min(list1)) 
View Code

四十九、Python 查找列表中最大元素

1 list1 = [10, 20, 4, 45, 99] 
2   
3 list1.sort() 
4   
5 print("最大元素為:", list1[-1]) 
View Code
1 list1 = [10, 20, 1, 45, 99] 
2   
3 print("最大元素為:", max(list1)) 
View Code

五十、Python 移除字符串中的指定位置字符

 1 test_str = "Runoob"
 2   
 3 # 輸出原始字符串
 4 print ("原始字符串為 : " + test_str) 
 5   
 6 # 移除第三個字符 n
 7 new_str = "" 
 8   
 9 for i in range(0, len(test_str)): 
10     if i != 2: 
11         new_str = new_str + test_str[i] 
12 
13 print ("字符串移除后為 : " + new_str) 
View Code
1 test_str = "Runoob"
2 new_str = test_str.replace(test_str[3], "", 1)
3 print(new_str)
View Code
 1 str = 'Runoob'
 2 
 3 '''
 4 @param str 原字符串
 5 @paramnum 要移除的位置
 6 @return 移除后的字符串
 7 '''
 8 
 9 def ff(str,num):
10     return str[:num] + str[num+1:];
11 print(ff(str,2));
12 print(ff(str,4));
View Code

五十一、Python 判斷字符串是否存在子字符串

1 def check(string, sub_str): 
2     if (string.find(sub_str) == -1): 
3         print("不存在!") 
4     else: 
5         print("存在!") 
6  
7 string = "www.runoob.com"
8 sub_str ="runoob"
9 check(string, sub_str)
View Code 

五十二、Python 判斷字符串長度

1 str = "runoob"
2 print(len(str))
View Code
1 def findLen(str): 
2     counter = 0
3     while str[counter:]: 
4         counter += 1
5     return counter 
6   
7 str = "runoob"
8 print(findLen(str))
View Code

五十三、Python 使用正則表達式提取字符串中的 URL

 1 import re 
 2   
 3 def Find(string): 
 4     # findall() 查找匹配正則表達式的字符串
 5     url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
 6     return url 
 7       
 8  
 9 string = 'Runoob 的網頁地址為:https://www.runoob.com,Google 的網頁地址為:https://www.google.com'
10 print("Urls: ", Find(string))
View Code

五十四、Python 將字符串作為代碼執行

 1 def exec_code(): 
 2     LOC = """ 
 3 def factorial(num): 
 4     fact=1 
 5     for i in range(1,num+1): 
 6         fact = fact*i 
 7     return fact 
 8 print(factorial(5)) 
 9 """
10     exec(LOC) 
11  
12 exec_code()
View Code

五十五、Python 字符串翻轉

1 str='Runoob'
2 print(str[::-1])
View Code
1 str='Runoob'
2 print(''.join(reversed(str)))
View Code

五十六、Python 對字符串切片及翻轉

 1 def rotate(input,d): 
 2   
 3     Lfirst = input[0 : d] 
 4     Lsecond = input[d :] 
 5     Rfirst = input[0 : len(input)-d] 
 6     Rsecond = input[len(input)-d : ] 
 7   
 8     print( "頭部切片翻轉 : ", (Lsecond + Lfirst) )
 9     print( "尾部切片翻轉 : ", (Rsecond + Rfirst) )
10  
11 if __name__ == "__main__": 
12     input = 'Runoob'
13     d=2  # 截取兩個字符
14     rotate(input,d)
View Code

五十七、Python 按鍵(key)或值(value)對字典進行排序

給定一個字典,然后按鍵(key)或值(value)對字典進行排序

 1 def dictionairy():  
 2   
 3     # 聲明字典
 4     key_value ={}     
 5  
 6     # 初始化
 7     key_value[2] = 56       
 8     key_value[1] = 2 
 9     key_value[5] = 12 
10     key_value[4] = 24
11     key_value[6] = 18      
12     key_value[3] = 323 
13  
14     print ("按鍵(key)排序:")   
15  
16     # sorted(key_value) 返回一個迭代器
17     # 字典按鍵排序
18     for i in sorted (key_value) : 
19         print ((i, key_value[i]), end =" ") 
20   
21 def main(): 
22     # 調用函數
23     dictionairy()              
24       
25 # 主函數
26 if __name__=="__main__":      
27     main()
View Code
 1 def dictionairy():  
 2  
 3     # 聲明字典
 4     key_value ={}     
 5  
 6     # 初始化
 7     key_value[2] = 56       
 8     key_value[1] = 2 
 9     key_value[5] = 12 
10     key_value[4] = 24
11     key_value[6] = 18      
12     key_value[3] = 323 
13  
14  
15     print ("按值(value)排序:")   
16     print(sorted(key_value.items(), key = lambda kv:(kv[1], kv[0])))     
17    
18 def main(): 
19     dictionairy()             
20       
21 if __name__=="__main__":       
22     main()
View Code
 1 lis = [{ "name" : "Taobao", "age" : 100},  
 2 { "name" : "Runoob", "age" : 7 }, 
 3 { "name" : "Google", "age" : 100 }, 
 4 { "name" : "Wiki" , "age" : 200 }] 
 5   
 6 # 通過 age 升序排序
 7 print ("列表通過 age 升序排序: ")
 8 print (sorted(lis, key = lambda i: i['age']) )
 9   
10 print ("\r") 
11   
12 # 先按 age 排序,再按 name 排序
13 print ("列表通過 age 和 name 排序: ")
14 print (sorted(lis, key = lambda i: (i['age'], i['name'])) )
15   
16 print ("\r") 
17   
18 # 按 age 降序排序
19 print ("列表通過 age 降序排序: ")
20 print (sorted(lis, key = lambda i: i['age'],reverse=True) )
View Code

五十八、Python 計算字典值之和

 1 def returnSum(myDict): 
 2       
 3     sum = 0
 4     for i in myDict: 
 5         sum = sum + myDict[i] 
 6       
 7     return sum
 8   
 9 dict = {'a': 100, 'b':200, 'c':300} 
10 print("Sum :", returnSum(dict))
View Code

五十九、Python 移除字典點鍵值(key/value)對

實例 1 : 使用 del 移除

 1 test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4} 
 2   
 3 # 輸出原始的字典
 4 print ("字典移除前 : " + str(test_dict)) 
 5   
 6 # 使用 del 移除 Zhihu
 7 del test_dict['Zhihu'] 
 8   
 9 # 輸出移除后的字典
10 print ("字典移除后 : " + str(test_dict)) 
11   
12 # 移除沒有的 key 會報錯
13 #del test_dict['Baidu']
View Code

實例 2 : 使用 pop() 移除

 1 test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4} 
 2   
 3 # 輸出原始的字典
 4 print ("字典移除前 : " + str(test_dict)) 
 5   
 6 # 使用 pop 移除 Zhihu
 7 removed_value = test_dict.pop('Zhihu') 
 8   
 9 # 輸出移除后的字典
10 print ("字典移除后 : " + str(test_dict)) 
11   
12 print ("移除的 key 對應的 value 為 : " + str(removed_value)) 
13   
14 print ('\r') 
15   
16 # 使用 pop() 移除沒有的 key 不會發生異常,我們可以自定義提示信息
17 removed_value = test_dict.pop('Baidu', '沒有該鍵(key)') 
18   
19 # 輸出移除后的字典
20 print ("字典移除后 : " + str(test_dict)) 
21 print ("移除的值為 : " + str(removed_value))
View Code

實例 3 : 使用 items() 移除

 1 test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4} 
 2   
 3 # 輸出原始的字典
 4 print ("字典移除前 : " + str(test_dict)) 
 5   
 6 # 使用 pop 移除 Zhihu
 7 new_dict = {key:val for key, val in test_dict.items() if key != 'Zhihu'} 
 8   
 9   
10 # 輸出移除后的字典
11 print ("字典移除后 : " + str(new_dict))
View Code

六十、Python 合並字典

給定一個字典,然后計算它們所有數字值的和。

實例 1 : 使用 update() 方法,第二個參數合並第一個參數

 1 def Merge(dict1, dict2): 
 2     return(dict2.update(dict1)) 
 3       
 4 # 兩個字典
 5 dict1 = {'a': 10, 'b': 8} 
 6 dict2 = {'d': 6, 'c': 4} 
 7   
 8 # 返回  None 
 9 print(Merge(dict1, dict2)) 
10   
11 # dict2 合並了 dict1
12 print(dict2)
View Code

實例 2 : 使用 **,函數將參數以字典的形式導入

1 def Merge(dict1, dict2): 
2     res = {**dict1, **dict2} 
3     return res 
4       
5 # 兩個字典
6 dict1 = {'a': 10, 'b': 8} 
7 dict2 = {'d': 6, 'c': 4} 
8 dict3 = Merge(dict1, dict2) 
9 print(dict3)
View Code

六十一、Python 將字符串的時間轉換為時間戳

 1 import time
 2  
 3 a1 = "2019-5-10 23:40:00"
 4 # 先轉換為時間數組
 5 timeArray = time.strptime(a1, "%Y-%m-%d %H:%M:%S")
 6  
 7 # 轉換為時間戳
 8 timeStamp = int(time.mktime(timeArray))
 9 print(timeStamp)
10  
11  
12 # 格式轉換 - 轉為 /
13 a2 = "2019/5/10 23:40:00"
14 # 先轉換為時間數組,然后轉換為其他格式
15 timeArray = time.strptime(a2, "%Y-%m-%d %H:%M:%S")
16 otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
17 print(otherStyleTime)
View Code

六十二、Python 獲取幾天前的時間

 1 import time
 2 import datetime
 3  
 4 # 先獲得時間數組格式的日期
 5 threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))
 6 # 轉換為時間戳
 7 timeStamp = int(time.mktime(threeDayAgo.timetuple()))
 8 # 轉換為其他字符串格式
 9 otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
10 print(otherStyleTime)
View Code
1 import time
2 import datetime
3  
4 #給定時間戳
5 timeStamp = 1557502800
6 dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
7 threeDayAgo = dateArray - datetime.timedelta(days = 3)
8 print(threeDayAgo)
View Code

六十三、Python 將時間戳轉換為指定格式日期

1 import time
2  
3 # 獲得當前時間時間戳
4 now = int(time.time())
5 #轉換為其他日期格式,如:"%Y-%m-%d %H:%M:%S"
6 timeArray = time.localtime(now)
7 otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
8 print(otherStyleTime)
View Code
1 import datetime
2  
3 # 獲得當前時間
4 now = datetime.datetime.now()
5 # 轉換為指定的格式
6 otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
7 print(otherStyleTime)
View Code
1 import time
2  
3 timeStamp = 1557502800
4 timeArray = time.localtime(timeStamp)
5 otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
6 print(otherStyleTime)
View Code
1 import datetime
2  
3 timeStamp = 1557502800
4 dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
5 otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
6 print(otherStyleTime)
View Code

六十四、Python 打印自己設計的字體

  1 name = "RUNOOB"
  2   
  3 # 接收用戶輸入
  4 # name = input("輸入你的名字: \n\n") 
  5   
  6 lngth = len(name) 
  7 l = "" 
  8   
  9 for x in range(0, lngth): 
 10     c = name[x] 
 11     c = c.upper() 
 12       
 13     if (c == "A"): 
 14         print("..######..\n..#....#..\n..######..", end = " ") 
 15         print("\n..#....#..\n..#....#..\n\n") 
 16           
 17     elif (c == "B"): 
 18         print("..######..\n..#....#..\n..#####...", end = " ") 
 19         print("\n..#....#..\n..######..\n\n") 
 20           
 21     elif (c == "C"): 
 22         print("..######..\n..#.......\n..#.......", end = " ") 
 23         print("\n..#.......\n..######..\n\n") 
 24           
 25     elif (c == "D"): 
 26         print("..#####...\n..#....#..\n..#....#..", end = " ") 
 27         print("\n..#....#..\n..#####...\n\n") 
 28           
 29     elif (c == "E"): 
 30         print("..######..\n..#.......\n..#####...", end = " ") 
 31         print("\n..#.......\n..######..\n\n") 
 32           
 33     elif (c == "F"): 
 34         print("..######..\n..#.......\n..#####...", end = " ") 
 35         print("\n..#.......\n..#.......\n\n") 
 36           
 37     elif (c == "G"): 
 38         print("..######..\n..#.......\n..#.####..", end = " ") 
 39         print("\n..#....#..\n..#####...\n\n") 
 40           
 41     elif (c == "H"): 
 42         print("..#....#..\n..#....#..\n..######..", end = " ") 
 43         print("\n..#....#..\n..#....#..\n\n") 
 44           
 45     elif (c == "I"): 
 46         print("..######..\n....##....\n....##....", end = " ") 
 47         print("\n....##....\n..######..\n\n") 
 48           
 49     elif (c == "J"): 
 50         print("..######..\n....##....\n....##....", end = " ") 
 51         print("\n..#.##....\n..####....\n\n") 
 52           
 53     elif (c == "K"): 
 54         print("..#...#...\n..#..#....\n..##......", end = " ") 
 55         print("\n..#..#....\n..#...#...\n\n") 
 56           
 57     elif (c == "L"): 
 58         print("..#.......\n..#.......\n..#.......", end = " ") 
 59         print("\n..#.......\n..######..\n\n") 
 60           
 61     elif (c == "M"): 
 62         print("..#....#..\n..##..##..\n..#.##.#..", end = " ") 
 63         print("\n..#....#..\n..#....#..\n\n") 
 64           
 65     elif (c == "N"): 
 66         print("..#....#..\n..##...#..\n..#.#..#..", end = " ") 
 67         print("\n..#..#.#..\n..#...##..\n\n") 
 68           
 69     elif (c == "O"): 
 70         print("..######..\n..#....#..\n..#....#..", end = " ") 
 71         print("\n..#....#..\n..######..\n\n") 
 72           
 73     elif (c == "P"): 
 74         print("..######..\n..#....#..\n..######..", end = " ") 
 75         print("\n..#.......\n..#.......\n\n") 
 76           
 77     elif (c == "Q"): 
 78         print("..######..\n..#....#..\n..#.#..#..", end = " ") 
 79         print("\n..#..#.#..\n..######..\n\n") 
 80           
 81     elif (c == "R"): 
 82         print("..######..\n..#....#..\n..#.##...", end = " ") 
 83         print("\n..#...#...\n..#....#..\n\n") 
 84           
 85     elif (c == "S"): 
 86         print("..######..\n..#.......\n..######..", end = " ") 
 87         print("\n.......#..\n..######..\n\n") 
 88           
 89     elif (c == "T"): 
 90         print("..######..\n....##....\n....##....", end = " ") 
 91         print("\n....##....\n....##....\n\n") 
 92           
 93     elif (c == "U"): 
 94         print("..#....#..\n..#....#..\n..#....#..", end = " ") 
 95         print("\n..#....#..\n..######..\n\n") 
 96           
 97     elif (c == "V"): 
 98         print("..#....#..\n..#....#..\n..#....#..", end = " ") 
 99         print("\n...#..#...\n....##....\n\n") 
100           
101     elif (c == "W"): 
102         print("..#....#..\n..#....#..\n..#.##.#..", end = " ") 
103         print("\n..##..##..\n..#....#..\n\n") 
104           
105     elif (c == "X"): 
106         print("..#....#..\n...#..#...\n....##....", end = " ") 
107         print("\n...#..#...\n..#....#..\n\n") 
108           
109     elif (c == "Y"): 
110         print("..#....#..\n...#..#...\n....##....", end = " ") 
111         print("\n....##....\n....##....\n\n") 
112           
113     elif (c == "Z"): 
114         print("..######..\n......#...\n.....#....", end = " ") 
115         print("\n....#.....\n..######..\n\n") 
116           
117     elif (c == " "): 
118         print("..........\n..........\n..........", end = " ") 
119         print("\n..........\n\n") 
120           
121     elif (c == "."): 
122         print("----..----\n\n")
View Code

六十五、Python 二分查找

 

二分搜索是一種在有序數組中查找某一特定元素的搜索算法。搜索過程從數組的中間元素開始,如果中間元素正好是要查找的元素,則搜索過程結束;如果某一特定元素大於或者小於中間元素,則在數組大於或小於中間元素的那一半中查找,而且跟開始一樣從中間元素開始比較。如果在某一步驟數組為空,則代表找不到。這種搜索算法每一次比較都使搜索范圍縮小一半。

實例 : 遞歸

 1 # 返回 x 在 arr 中的索引,如果不存在返回 -1
 2 def binarySearch (arr, l, r, x): 
 3   
 4     # 基本判斷
 5     if r >= l: 
 6   
 7         mid = int(l + (r - l)/2)
 8   
 9         # 元素整好的中間位置
10         if arr[mid] == x: 
11             return mid 
12           
13         # 元素小於中間位置的元素,只需要再比較左邊的元素
14         elif arr[mid] > x: 
15             return binarySearch(arr, l, mid-1, x) 
16   
17         # 元素大於中間位置的元素,只需要再比較右邊的元素
18         else: 
19             return binarySearch(arr, mid+1, r, x) 
20   
21     else: 
22         # 不存在
23         return -1
24   
25 # 測試數組
26 arr = [ 2, 3, 4, 10, 40 ] 
27 x = 10
28   
29 # 函數調用
30 result = binarySearch(arr, 0, len(arr)-1, x) 
31   
32 if result != -1: 
33     print ("元素在數組中的索引為 %d" % result )
34 else: 
35     print ("元素不在數組中")
View Code

六十六、Python 線性查找

線性查找指按一定的順序檢查數組中每一個元素,直到找到所要尋找的特定值為止。

實例

 1 def search(arr, n, x): 
 2   
 3     for i in range (0, n): 
 4         if (arr[i] == x): 
 5             return i; 
 6     return -1; 
 7   
 8 # 在數組 arr 中查找字符 D
 9 arr = [ 'A', 'B', 'C', 'D', 'E' ]; 
10 x = 'D'; 
11 n = len(arr); 
12 result = search(arr, n, x) 
13 if(result == -1): 
14     print("元素不在數組中") 
15 else: 
16     print("元素在數組中的索引為", result);
View Code
 1 def LinearSearch(list):
 2     num = int(input('Number:\t'))
 3     counter = 0
 4     null = 0
 5 
 6     for i in list:
 7         if i == num:
 8             print('Find number {} in place {}.'.format(num, counter))
 9         else:
10             null += 1
11         counter += 1
12     if null == counter:
13         print('Don\'t find it.')
14 
15 list = [1, 2, 5, 7, 8, 34, 567, -1, 0, -1, -3, -9, 0]
16 LinearSearch(list)
View Code

六十七、Python 插入排序

插入排序(英語:Insertion Sort)是一種簡單直觀的排序算法。它的工作原理是通過構建有序序列,對於未排序數據,在已排序序列中從后向前掃描,找到相應位置並插入。

 

 1 def insertionSort(arr): 
 2   
 3     for i in range(1, len(arr)): 
 4   
 5         key = arr[i] 
 6   
 7         j = i-1
 8         while j >=0 and key < arr[j] : 
 9                 arr[j+1] = arr[j] 
10                 j -= 1
11         arr[j+1] = key 
12   
13   
14 arr = [12, 11, 13, 5, 6] 
15 insertionSort(arr) 
16 print ("排序后的數組:") 
17 for i in range(len(arr)): 
18     print ("%d" %arr[i])
View Code
 1 """插入排序
 2 InsertionSort.py"""
 3 
 4 # 一次往數組添加多個數字
 5 def AppendNumbers(array):
 6     num = input('Numbers:(split by spaces)\t').split()
 7     for i in num:
 8         array.append(int(i))
 9     print('排序前數組:{}.'.format(array))
10 
11 def InsertionSort(array):
12     AppendNumbers(array)  # 添加
13 
14     list = []
15     while True:
16         for i in array:
17             minimum = min(array)
18             if i == minimum:
19                 list.append(i)
20                 array.remove(i)  # 刪去最小值
21 
22         if array == []:
23             break
24 
25     print('排序后數組:{}.'.format(list))
26 
27 array = [6, 4, 45, -2, -1, 2, 4, 0, 1, 2, 3, 4, 5, 6, -4, -6,  7, 8, 8, 34, 0]
28 InsertionSort(array)
View Code
 1 arr = [1,12,2, 11, 13, 5, 6,18,4,9,-5,3,11] 
 2 
 3 def insertionSort(arr):
 4     #從要排序的列表第二個元素開始比較
 5     for i in range(1,len(arr)):
 6         j = i
 7         #從大到小比較,直到比較到第一個元素
 8         while j > 0:
 9             if arr[j] < arr[j-1]:
10                 arr[j-1],arr[j] = arr[j],arr[j-1]
11             j -= 1        
12     return arr
13 print(insertionSort(arr))
View Code

六十八、Python 快速排序

快速排序使用分治法(Divide and conquer)策略來把一個序列(list)分為較小和較大的2個子序列,然后遞歸地排序兩個子序列。

步驟為:

  • 挑選基准值:從數列中挑出一個元素,稱為"基准"(pivot);
  • 分割:重新排序數列,所有比基准值小的元素擺放在基准前面,所有比基准值大的元素擺在基准后面(與基准值相等的數可以到任何一邊)。在這個分割結束之后,對基准值的排序就已經完成;
  • 遞歸排序子序列:遞歸地將小於基准值元素的子序列和大於基准值元素的子序列排序。

遞歸到最底部的判斷條件是數列的大小是零或一,此時該數列顯然已經有序。

選取基准值有數種具體方法,此選取方法對排序的時間性能有決定性影響。

 

 1 def partition(arr,low,high): 
 2     i = ( low-1 )         # 最小元素索引
 3     pivot = arr[high]     
 4   
 5     for j in range(low , high): 
 6   
 7         # 當前元素小於或等於 pivot 
 8         if   arr[j] <= pivot: 
 9           
10             i = i+1 
11             arr[i],arr[j] = arr[j],arr[i] 
12   
13     arr[i+1],arr[high] = arr[high],arr[i+1] 
14     return ( i+1 ) 
15   
16  
17 # arr[] --> 排序數組
18 # low  --> 起始索引
19 # high  --> 結束索引
20   
21 # 快速排序函數
22 def quickSort(arr,low,high): 
23     if low < high: 
24   
25         pi = partition(arr,low,high) 
26   
27         quickSort(arr, low, pi-1) 
28         quickSort(arr, pi+1, high) 
29   
30 arr = [10, 7, 8, 9, 1, 5] 
31 n = len(arr) 
32 quickSort(arr,0,n-1) 
33 print ("排序后的數組:") 
34 for i in range(n): 
35     print ("%d" %arr[i]),
View Code

六十九、Python 選擇排序

選擇排序(Selection sort)是一種簡單直觀的排序算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再從剩余未排序元素中繼續尋找最小(大)元素,然后放到已排序序列的末尾。以此類推,直到所有元素均排序完畢。

 

 1 import sys 
 2 A = [64, 25, 12, 22, 11] 
 3   
 4 for i in range(len(A)): 
 5       
 6    
 7     min_idx = i 
 8     for j in range(i+1, len(A)): 
 9         if A[min_idx] > A[j]: 
10             min_idx = j 
11                 
12     A[i], A[min_idx] = A[min_idx], A[i] 
13   
14 print ("排序后的數組:") 
15 for i in range(len(A)): 
16     print("%d" %A[i]),
View Code
 1 """選擇排序
 2 Selectionsort.py"""
 3 
 4 # 以序號為依據
 5 def Selectionsort1():
 6     A = [-9, -8, 640, 25, 12, 22, 33, 23, 45, 11, -2, -5, 99, 0]
 7     for i in range(len(A)):
 8         min = i
 9         for j in range(i + 1, len(A)):  # 上一個值右邊的數組
10             if A[min] > A[j]:  # 使min為最小值,遇到比min小的值就賦值於min
11                 min = j
12 
13         A[i], A[min] = A[min], A[i]  # 交換最小值到左邊
14 
15     print ('Selectionsort1排序后的數組:', A)
16 
17 # 以數值為依據
18 def Selectionsort2():
19     A = [-9, -8, 640, 25, 12, 22, 33, 23, 45, 11, -2, -5, 99, 0]
20     counter = 0  # 記錄循環次數和位置
21     array = []
22 
23     for i in A:
24         counter += 1
25         for j in A[counter:]:  # 縮小范圍
26             if i > j:  # 使i為最小值
27                 i = j
28 
29             A.remove(i)
30             A.insert(counter - 1, i)
31             # 把最小值置於列表左邊,避免重復比較
32 
33         array.append(i)
34 
35     print('Selectionsort2排序后的數組:', array)
36 
37 Selectionsort1()
38 Selectionsort2()
View Code
 1 #待排序數組arr,排序方式order>0升序,order<0降序
 2 def selectSort(arr,order):
 3     rborder = len(arr)
 4     for i in range(0,rborder):
 5         p = i
 6         j = i+1
 7         while(j<rborder):
 8             if((arr[p]>arr[j]) and (int(order)>0)) or ((arr[p]<arr[j]) and (int(order)<0)):
 9                 p = j
10             j += 1
11         arr[i], arr[p] = arr[p], arr[i]
12         i += 1
13     return arr
14 
15 A = [64, 25, 12, 22, 11] 
16 print(selectSort(A, -1))
17 print(selectSort(A, 1))
View Code

七十、Python 冒泡排序

冒泡排序(Bubble Sort)也是一種簡單直觀的排序算法。它重復地走訪過要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。走訪數列的工作是重復地進行直到沒有再需要交換,也就是說該數列已經排序完成。這個算法的名字由來是因為越小的元素會經由交換慢慢"浮"到數列的頂端。

 1 def bubbleSort(arr):
 2     n = len(arr)
 3  
 4     # 遍歷所有數組元素
 5     for i in range(n):
 6  
 7         # Last i elements are already in place
 8         for j in range(0, n-i-1):
 9  
10             if arr[j] > arr[j+1] :
11                 arr[j], arr[j+1] = arr[j+1], arr[j]
12  
13 arr = [64, 34, 25, 12, 22, 11, 90]
14  
15 bubbleSort(arr)
16  
17 print ("排序后的數組:")
18 for i in range(len(arr)):
19     print ("%d" %arr[i]),
View Code

七十一、Python 歸並排序

歸並排序(英語:Merge sort,或mergesort),是創建在歸並操作上的一種有效的排序算法。該算法是采用分治法(Divide and Conquer)的一個非常典型的應用。

分治法:

  • 分割:遞歸地把當前序列平均分割成兩半。
  • 集成:在保持元素順序的同時將上一步得到的子序列集成到一起(歸並)。

 

 1 def merge(arr, l, m, r): 
 2     n1 = m - l + 1
 3     n2 = r- m 
 4   
 5     # 創建臨時數組
 6     L = [0] * (n1)
 7     R = [0] * (n2)
 8   
 9     # 拷貝數據到臨時數組 arrays L[] 和 R[] 
10     for i in range(0 , n1): 
11         L[i] = arr[l + i] 
12   
13     for j in range(0 , n2): 
14         R[j] = arr[m + 1 + j] 
15   
16     # 歸並臨時數組到 arr[l..r] 
17     i = 0     # 初始化第一個子數組的索引
18     j = 0     # 初始化第二個子數組的索引
19     k = l     # 初始歸並子數組的索引
20   
21     while i < n1 and j < n2 : 
22         if L[i] <= R[j]: 
23             arr[k] = L[i] 
24             i += 1
25         else: 
26             arr[k] = R[j] 
27             j += 1
28         k += 1
29   
30     # 拷貝 L[] 的保留元素
31     while i < n1: 
32         arr[k] = L[i] 
33         i += 1
34         k += 1
35   
36     # 拷貝 R[] 的保留元素
37     while j < n2: 
38         arr[k] = R[j] 
39         j += 1
40         k += 1
41   
42 def mergeSort(arr,l,r): 
43     if l < r: 
44   
45         
46         m = int((l+(r-1))/2)
47   
48        
49         mergeSort(arr, l, m) 
50         mergeSort(arr, m+1, r) 
51         merge(arr, l, m, r) 
52   
53   
54 arr = [12, 11, 13, 5, 6, 7] 
55 n = len(arr) 
56 print ("給定的數組") 
57 for i in range(n): 
58     print ("%d" %arr[i]), 
59   
60 mergeSort(arr,0,n-1) 
61 print ("\n\n排序后的數組") 
62 for i in range(n): 
63     print ("%d" %arr[i]),
View Code

七十二、Python 堆排序

堆排序(Heapsort)是指利用堆這種數據結構所設計的一種排序算法。堆積是一個近似完全二叉樹的結構,並同時滿足堆積的性質:即子結點的鍵值或索引總是小於(或者大於)它的父節點。堆排序可以說是一種利用堆的概念來排序的選擇排序。

 

 1 def heapify(arr, n, i): 
 2     largest = i  
 3     l = 2 * i + 1     # left = 2*i + 1 
 4     r = 2 * i + 2     # right = 2*i + 2 
 5   
 6     if l < n and arr[i] < arr[l]: 
 7         largest = l 
 8   
 9     if r < n and arr[largest] < arr[r]: 
10         largest = r 
11   
12     if largest != i: 
13         arr[i],arr[largest] = arr[largest],arr[i]  # 交換
14   
15         heapify(arr, n, largest) 
16   
17 def heapSort(arr): 
18     n = len(arr) 
19   
20     # Build a maxheap. 
21     for i in range(n, -1, -1): 
22         heapify(arr, n, i) 
23   
24     # 一個個交換元素
25     for i in range(n-1, 0, -1): 
26         arr[i], arr[0] = arr[0], arr[i]   # 交換
27         heapify(arr, i, 0) 
28   
29 arr = [ 12, 11, 13, 5, 6, 7] 
30 heapSort(arr) 
31 n = len(arr) 
32 print ("排序后") 
33 for i in range(n): 
34     print ("%d" %arr[i]),
View Code

七十三、Python 計數排序

計數排序的核心在於將輸入的數據值轉化為鍵存儲在額外開辟的數組空間中。作為一種線性時間復雜度的排序,計數排序要求輸入的數據必須是有確定范圍的整數。

 

 1 def countSort(arr): 
 2   
 3     output = [0 for i in range(256)] 
 4   
 5     count = [0 for i in range(256)] 
 6   
 7     ans = ["" for _ in arr] 
 8   
 9     for i in arr: 
10         count[ord(i)] += 1
11   
12     for i in range(256): 
13         count[i] += count[i-1] 
14   
15     for i in range(len(arr)): 
16         output[count[ord(arr[i])]-1] = arr[i] 
17         count[ord(arr[i])] -= 1
18   
19     for i in range(len(arr)): 
20         ans[i] = output[i] 
21     return ans  
22   
23 arr = "wwwrunoobcom"
24 ans = countSort(arr) 
25 print ( "字符數組排序 %s"  %("".join(ans)) )
View Code

七十四、Python 希爾排序

希爾排序,也稱遞減增量排序算法,是插入排序的一種更高效的改進版本。但希爾排序是非穩定排序算法。

希爾排序的基本思想是:先將整個待排序的記錄序列分割成為若干子序列分別進行直接插入排序,待整個序列中的記錄"基本有序"時,再對全體記錄進行依次直接插入排序。

 

 1 def shellSort(arr): 
 2   
 3     n = len(arr)
 4     gap = int(n/2)
 5   
 6     while gap > 0: 
 7   
 8         for i in range(gap,n): 
 9   
10             temp = arr[i] 
11             j = i 
12             while  j >= gap and arr[j-gap] >temp: 
13                 arr[j] = arr[j-gap] 
14                 j -= gap 
15             arr[j] = temp 
16         gap = int(gap/2)
17   
18 arr = [ 12, 34, 54, 2, 3] 
19   
20 n = len(arr) 
21 print ("排序前:") 
22 for i in range(n): 
23     print(arr[i]), 
24   
25 shellSort(arr) 
26   
27 print ("\n排序后:") 
28 for i in range(n): 
29     print(arr[i]),
View Code

七十五、Python 拓撲排序

對一個有向無環圖(Directed Acyclic Graph簡稱DAG)G進行拓撲排序,是將G中所有頂點排成一個線性序列,使得圖中任意一對頂點u和v,若邊(u,v)∈E(G),則u在線性序列中出現在v之前。通常,這樣的線性序列稱為滿足拓撲次序(Topological Order)的序列,簡稱拓撲序列。簡單的說,由某個集合上的一個偏序得到該集合上的一個全序,這個操作稱之為拓撲排序。

在圖論中,由一個有向無環圖的頂點組成的序列,當且僅當滿足下列條件時,稱為該圖的一個拓撲排序(英語:Topological sorting):

  • 每個頂點出現且只出現一次;
  • 若A在序列中排在B的前面,則在圖中不存在從B到A的路徑。

實例 

 1 from collections import defaultdict 
 2  
 3 class Graph: 
 4     def __init__(self,vertices): 
 5         self.graph = defaultdict(list) 
 6         self.V = vertices
 7   
 8     def addEdge(self,u,v): 
 9         self.graph[u].append(v) 
10   
11     def topologicalSortUtil(self,v,visited,stack): 
12   
13         visited[v] = True
14   
15         for i in self.graph[v]: 
16             if visited[i] == False: 
17                 self.topologicalSortUtil(i,visited,stack) 
18   
19         stack.insert(0,v) 
20   
21     def topologicalSort(self): 
22         visited = [False]*self.V 
23         stack =[] 
24   
25         for i in range(self.V): 
26             if visited[i] == False: 
27                 self.topologicalSortUtil(i,visited,stack) 
28   
29         print (stack) 
30   
31 g= Graph(6) 
32 g.addEdge(5, 2); 
33 g.addEdge(5, 0); 
34 g.addEdge(4, 0); 
35 g.addEdge(4, 1); 
36 g.addEdge(2, 3); 
37 g.addEdge(3, 1); 
38   
39 print ("拓撲排序結果:")
40 g.topologicalSort()
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM