程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Python3 实例

发布于2019-08-05 11:53     阅读(428)     评论(0)     点赞(4)     收藏(3)


一直以来,总想写些什么,但不知从何处落笔。

今儿个仓促,也不知道怎么写,就把手里练习过的例子,整理了一下。

希望对初学者有用,都是非常基础的例子,很适合初练。

好了,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

 



所属网站分类: 技术文章 > 博客

作者:小姐可不可以

链接:https://www.pythonheidong.com/blog/article/4446/8d019935d9476f4aecc0/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)