python之实例分析

2024-01-30 14:01:54 浏览数 (1)

实例一、温度转换

温度刻画的两种不同体系,是摄氏度和华氏度,

摄氏度:以1标准大气压下水的结冰点为0度,沸点为100度,中国等世界大多数国家使用; 华氏度:以1标准大气压下水的结冰点为32度,沸点为212度,英美等国家使用; 系,

1,输入:输入带华氏或摄氏标致的温度值,, 2,处理:根据温度标致选择适当的温度转换算法, 3,输出:输出带摄氏或华氏的温度值, <F标识华氏度,C表示摄氏度,

华氏转换公式:F=C*1.8 32 摄氏转换公式:C=(F-32)/1.8

代码语言:javascript复制
#TempConvert.py
TempStr = input("请输入带有符号的温度值:")
if TempStr[-1] in ['F','f']:
    C = (eval(TempStr[0:1])-32)/1.8
    print('转换后的温度是{:.2f}C'.format(C))
elif TempStr[-1] in ['C','c']:
    F = 1.8*eval(TempStr[0:1]) 32
    print("转换后的温度是{:.2f}F".format(F))
else:
    print("输入格式错误")

温度转换问题是各类转换问题的代表性问题,如货币转换、长度转换、重量转换、面积转换等

实例二、天天向上的力量

问题1:千分之一的力量 -一年365天,每天进步千分之一,累计进步多少呢? -一年365天,每天退步千分之一,累计剩下多少呢?

代码语言:javascript复制
#DayDayUpQ1.py
dayup=pow(1.001,365)
daydown=pow(0.999,365)
print("向上:{:.2f},向下:{:.2f}".format(dayup,daydown))

问题2:千分之五和白分之一的力量 -一年365天,每天进步千分之五或百分之一,累计退步多少呢? -一年365天,每天退步千分之五或百分之一,累计退步多少呢?

代码语言:javascript复制
#DayDayUpQ2.py
dayfactor=0.005
dayup=pow(1 dayfactor,365)
daydown=pow(1-dayfactor,365)
print("向上:{:.2f},向下:{:.2f}".format(dayup,daydown))
代码语言:javascript复制
#DayDayUpQ2.py
dayfactor=0.01
dayup=pow(1 dayfactor,365)
daydown=pow(1-dayfactor,365)
print("向上:{:.2f},向下:{:.2f}".format(dayup,daydown))

问题3:工作日的力量 -一年365天,一周5个公作日,每天进步1% -一年365天,一周2个公作日,每天退步1% -这种工作日的力量,如何呢?

代码语言:javascript复制
#DayDayUp3.py
dayup=1.0
dayfactor=0.01
for i in range(365):
	if i % 7 in [6,0]:
		dayup=dayup*(1-dayfactor)
	else:
		dayup=dayup*(1 dayfactor)
print("工作日的力量:{:.2f}".format(dayup))

问题4:工作日的努力 -工作日模式要努力到什么水平,才能与每天努力1%一样? 假设两个人 -A君:一年365天,每天进步1%,不停歇 -B君:一年365天,每周工作5天休息2天,休息日下降1%,要多努力呢?

代码语言:javascript复制
#DayDayUpQ4.py
def dayUP(df):
	dayup=1
	for i in range(365):
		if i % 7 in [6,0]:
			dayup=dayup*(1-0.01)
		else:
			dayup=dayup*(1 df)
	return dayup
dayfactor=0.01
while dayUP(dayfactor)<37.78:
	dayfactor =0.001
print("工作日的努力参数是:{:.3f}".format(dayfactor))

实例三、python蟒蛇的绘制

参考turtle库专题内容:python蟒蛇绘制

实例四、文本进度条

1、文本进度条 简单的开始

代码语言:javascript复制
#TextProBarV1.py
import time
scale = 10
print("------执行开始------")
for i in range(scale 1):
    a = '*' * i
    b = '.' * (scale - i)
    c = (i/scale)*100
    print("{:^3.0f}%[{}->{}]".format(c,a,b))
    time.sleep(0.1)
print("------执行结束------")

2、文本进度条 单行动态刷新

代码语言:javascript复制
#TextProBarV2.py
import time
for i in range(101):
    print("r{:3}%".format(i), end="")
    time.sleep(0.1)

3、文本进度条 实例完整效果

代码语言:javascript复制
#TextProBarV3.py
import time
scale = 50
print("执行开始".center(scale//2, "-"))
start = time.perf_counter()
for i in range(scale 1):
    a = '*' * i
    b = '.' * (scale - i)
    c = (i/scale)*100
    dur = time.perf_counter() - start
    print("r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end='')
    time.sleep(0.1)
print("n" "执行结束".center(scale//2,'-'))

实例五、身体质量指数BMI

国际:

代码语言:javascript复制
#CalBMIv1.py
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
who = ""
if bmi < 18.5:
    who = "偏瘦"
elif 18.5 <= bmi < 25:
    who = "正常"
elif 25 <= bmi < 30:
    who = "偏胖"
else:
    who = "肥胖"
print("BMI 指标为:国际'{0}'".format(who))

国内:

代码语言:javascript复制
#CalBMIv2.py
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
nat = ""
if bmi < 18.5:
    nat = "偏瘦"
elif 18.5 <= bmi < 24:
    nat = "正常"
elif 24 <= bmi < 28:
    nat = "偏胖"
else:
    nat = "肥胖"
print("BMI 指标为:国内'{0}'".format(nat))

两个同时:

代码语言:javascript复制
#CalBMIv3.py
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
who, nat = "", ""
if bmi < 18.5:
    who, nat = "偏瘦", "偏瘦"
elif 18.5 <= bmi < 24:
    who, nat = "正常", "正常"
elif 24 <= bmi < 25:
    who, nat = "正常", "偏胖"
elif 25 <= bmi < 28:
    who, nat = "偏胖", "偏胖"
elif 28 <= bmi < 30:
    who, nat = "偏胖", "肥胖"
else:
    who, nat = "肥胖", "肥胖"
print("BMI 指标为:国际'{0}', 国内'{1}'".format(who, nat))

实例六、圆周率的计算

公式法

代码语言:javascript复制
#CalPiV1.py
pi = 0
N = 100
for k in range(N):
    pi  = 1/pow(16,k)*( 
              4/(8*k 1) - 2/(8*k 4) - 
              1/(8*k 5) - 1/(8*k 6) ) 
print("圆周率值是: {}".format(pi))

蒙特卡罗方法

代码语言:javascript复制
#CalPiV2.py
from random import random
from time import perf_counter
DARTS = 1000*1000
hits = 0.0
start = perf_counter()
for i in range(1, DARTS 1):
    x, y = random(), random()
    dist = pow(x ** 2   y ** 2, 0.5)
    if dist <= 1.0:
        hits = hits   1
pi = 4 * (hits/DARTS)
print("圆周率值是: {}".format(pi))
print("运行时间是: {:.5f}s".format(perf_counter() - start))

实例七、七段数码管绘制

版本一:

代码语言:javascript复制
#SevenDigitsDrawV1.py
import turtle
def drawLine(draw):   #绘制单段数码管
    turtle.pendown() if draw else turtle.penup()
    turtle.fd(40)
    turtle.right(90)
def drawDigit(digit): #根据数字绘制七段数码管
    drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,3,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,6,8] else drawLine(False)
    turtle.left(90)
    drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False)
    drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False)
    turtle.left(180)
    turtle.penup()
    turtle.fd(20) 
def drawDate(date):  #获得要输出的数字
    for i in date:
        drawDigit(eval(i))  #通过eval()函数将数字变为整数
def main():
    turtle.setup(800, 350, 200, 200)
    turtle.penup()
    turtle.fd(-300)
    turtle.pensize(5)
    drawDate('20181010')
    turtle.hideturtle()
    turtle.done()
main()

版本二:

代码语言:javascript复制
#SevenDigitsDrawV2.py
import turtle, time
def drawGap(): #绘制数码管间隔
    turtle.penup()
    turtle.fd(5)
def drawLine(draw):   #绘制单段数码管
    drawGap()
    turtle.pendown() if draw else turtle.penup()
    turtle.fd(40)
    drawGap()
    turtle.right(90)
def drawDigit(d): #根据数字绘制七段数码管
    drawLine(True) if d in [2,3,4,5,6,8,9] else drawLine(False)
    drawLine(True) if d in [0,1,3,4,5,6,7,8,9] else drawLine(False)
    drawLine(True) if d in [0,2,3,5,6,8,9] else drawLine(False)
    drawLine(True) if d in [0,2,6,8] else drawLine(False)
    turtle.left(90)
    drawLine(True) if d in [0,4,5,6,8,9] else drawLine(False)
    drawLine(True) if d in [0,2,3,5,6,7,8,9] else drawLine(False)
    drawLine(True) if d in [0,1,2,3,4,7,8,9] else drawLine(False)
    turtle.left(180)
    turtle.penup()
    turtle.fd(20)
def drawDate(date):
    turtle.pencolor("red")
    for i in date:
        if i == '-':
            turtle.write('年',font=("Arial", 18, "normal"))
            turtle.pencolor("green")
            turtle.fd(40)
        elif i == '=':
            turtle.write('月',font=("Arial", 18, "normal"))
            turtle.pencolor("blue")
            turtle.fd(40)
        elif i == ' ':
            turtle.write('日',font=("Arial", 18, "normal"))
        else:
            drawDigit(eval(i))
def main():
    turtle.setup(800, 350, 200, 200)
    turtle.penup()
    turtle.fd(-350)
    turtle.pensize(5)
#    drawDate('2018-10=10 ')
    drawDate(time.strftime('%Y-%m=%d ',time.gmtime()))
    turtle.hideturtle()
    turtle.done()
main()

实例八、科赫曲线绘制

代码语言:javascript复制
#KochDrawV1.py
import turtle
def koch(size, n):
    if n == 0:
        turtle.fd(size)
    else:
        for angle in [0, 60, -120, 60]:
           turtle.left(angle)
           koch(size/3, n-1)
def main():
    turtle.setup(800,400)
    turtle.penup()
    turtle.goto(-300, -50)
    turtle.pendown()
    turtle.pensize(2)
    koch(600,3)     # 0阶科赫曲线长度,阶数
    turtle.hideturtle()
main()

科赫雪花绘制

代码语言:javascript复制
#KochDrawV2.py
import turtle
def koch(size, n):
    if n == 0:
        turtle.fd(size)
    else:
        for angle in [0, 60, -120, 60]:
           turtle.left(angle)
           koch(size/3, n-1)
def main():
    turtle.setup(600,600)
    turtle.penup()
    turtle.goto(-200, 100)
    turtle.pendown()
    turtle.pensize(2)
    level = 3      # 3阶科赫雪花,阶数
    koch(400,level)     
    turtle.right(120)
    koch(400,level)
    turtle.right(120)
    koch(400,level)
    turtle.hideturtle()
main()

实例九、基本统计值计算

代码语言:javascript复制
#CalStatisticsV1.py
def getNum():       #获取用户不定长度的输入
    nums = []
    iNumStr = input("请输入数字(回车退出): ")
    while iNumStr != "":
        nums.append(eval(iNumStr))
        iNumStr = input("请输入数字(回车退出): ")
    return nums

def mean(numbers):  #计算平均值
    s = 0.0
    for num in numbers:
        s = s   num
    return s / len(numbers)

def dev(numbers, mean): #计算方差
    sdev = 0.0
    for num in numbers:
        sdev = sdev   (num - mean)**2
    return pow(sdev / (len(numbers)-1), 0.5)

def median(numbers):    #计算中位数
    sorted(numbers)
    size = len(numbers)
    if size % 2 == 0:
        med = (numbers[size//2-1]   numbers[size//2])/2
    else:
        med = numbers[size//2]
    return med

n =  getNum() #主体函数
m =  mean(n)
print("平均值:{},方差:{:.2},中位数:{}.".format(m, dev(n,m),median(n)))

实例10、文本词频统计

Hamlet词频统计

代码语言:javascript复制
#CalHamletV1.py
def getText():
    txt = open("hamlet.txt", "r").read()
    txt = txt.lower()
    for ch in '!"#$%&()* ,-./:;<=>?@[\]^_‘{|}~':
        txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
    return txt

hamletTxt = getText()
words  = hamletTxt.split()
counts = {}
for word in words:			
    counts[word] = counts.get(word,0)   1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(10):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))

三国演义》人物出场统计(上)(含《三国演义》原文文本)

代码语言:javascript复制
#CalThreeKingdomsV1.py
import jieba
txt = open("threekingdoms.txt", "r", encoding='utf-8').read()
words  = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
    else:
        counts[word] = counts.get(word,0)   1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(15):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))

《三国演义》人物出场统计(下)(含《三国演义》原文文本)

代码语言:javascript复制
#CalThreeKingdomsV2.py
import jieba
excludes = {"将军","却说","荆州","二人","不可","不能","如此"}
txt = open("threekingdoms.txt", "r", encoding='utf-8').read()
words  = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
    elif word == "诸葛亮" or word == "孔明曰":
        rword = "孔明"
    elif word == "关公" or word == "云长":
        rword = "关羽"
    elif word == "玄德" or word == "玄德曰":
        rword = "刘备"
    elif word == "孟德" or word == "丞相":
        rword = "曹操"
    else:
        rword = word
    counts[rword] = counts.get(rword,0)   1
for word in excludes:
    del counts[word]
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(10):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))

0 人点赞