Python程序设计(基础与应用) 第二部分,基础程序练习

Python基础练习

习题1 天天向上

WeekNamePrint1.py
weekStr = "星期一星期二星期三星期四星期五星期六星期日"
weekId = eval(input("请输入星期数字(1-7):"))
pos = (weekId - 1) * 3
print(weekStr[pos: pos+3])

习题2 天天向上2

weekStr = "一二三四五六日"
weekId = eval(input("请输入星期数字(1-7):"))
print("星期"+ weekStr[weekId-1])

习题3 工作日的力量

 #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 工作日的努力量

#DayDayUp4.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 4.63 < 37.78:
   dayfactor += 0.001
print("工作日努力的力量:{:.3f}".format(dayfactor))

习题5 星座

#星座(unicode编码)
for i in range(12):
   print(chr(9800+i), end="  ")   # end为空,表示不换行

习题6 圆周率计算

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))

习题7 圆周率计算(random)

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()))

习题8 单行动态刷新

import time
for i in range(101):
    print("\r{:3}%".format(i),end="")
    time.sleep(0.5)

习题9 三国出场人物统计

import jieba
txt = open("threekingdoms.txt","r", encoding="utf-8").read()
excludes = {"将军","却说","荆州","二人","不可","不能","如此"}
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 exclides:
    del counts[word]
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(10):
    word, counts = items[i]
    print("{0:<10}{1:>5}".format(word, count))

习题10 文本词频统计

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

习题11 体育竞技分析

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))
   #MatchAnalysis.py
from random import random
def printIntro():
   print("这个程序模拟两个选手A和B的某种竞技比赛")
   print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
def getInputs():
   a = eval(input("请输入选手A的能力值(0-1): "))
   b = eval(input("请输入选手B的能力值(0-1): "))
   n = eval(input("模拟比赛的场次: "))
   return a, b, n
def simNGames(n, probA, probB):
   winsA, winsB = 0, 0
   for i in range(n):
       scoreA, scoreB = simOneGame(probA, probB)
       if scoreA > scoreB:
           winsA += 1
       else:
           winsB += 1
   return winsA, winsB
def gameOver(a,b):
   return a==15 or b==15
def simOneGame(probA, probB):
   scoreA, scoreB = 0, 0
   serving = "A"
   while not gameOver(scoreA, scoreB):
       if serving == "A":
           if random() < probA:
               scoreA += 1
           else:
               serving="B"
       else:
           if random() < probB:
               scoreB += 1
           else:
               serving="A"
   return scoreA, scoreB
def printSummary(winsA, winsB):
   n = winsA + winsB
   print("竞技分析开始,共模拟{}场比赛".format(n))
   print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA, winsA/n))
   print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB, winsB/n))
def main():
   printIntro()
   probA, probB, n = getInputs()
   winsA, winsB = simNGames(n, probA, probB)
   printSummary(winsA, winsB)
main()

习题12 文本进度条

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.5)
print("-----执行结束-----")

习题13 科赫雪花

#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()

习题14 自动轨迹读取

#AutoTraceDraw.py
import turtle as t
t.title('自动轨迹绘制')
t.setup(800, 600, 0, 0)
t.pencolor("red")
t.pensize(5)
#数据读取
datals = []
f = open("data.txt")
for line in f:
 line = line.replace("\n","")
 datals.append(list(map(eval, line.split(","))))
f.close()
#自动绘制
for i in range(len(datals)):
 t.pencolor(datals[i][3],datals[i][4],datals[i][5])
 t.fd(datals[i][0])
 if datals[i][1]:
     t.rt(datals[i][2])
 else:
     t.lt(datals[i][2])
     ```
### 习题15 进度条(plus)
```python
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.5)
print("\n"+"执行结束".center(scale//2,'_'))
### 习题16 身体质量指数BMI
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 = "偏胖", "肥胖"
print("BIM指标为:国际'{0}',国内'{1}'".format(who,nat))
 ```
### 习题17 蛇形绘制
***方法1***
```python
pythonDraw.py
import turtle
turtle.setup(650,350,200,200)
turtle.penup()                  # pu
turtle.fd(-250)                 # fd正向,bk反向,circle曲线前进
turtle.pendown()                # pd
turtle.pensize(25)
turtle.pencolor("purple")
turtle.seth(-40)                # seth仅改变方向
for i in range(4):              # 4:循环次数    range(n) 0~n-1 或 range(m,n) m~n-1
 turtle.circle(40,80)        # (半径,弧度)
 turtle.circle(-40,80)
turtle.circle(40,80/2)
turtle.fd(40)
turtle.circle(16,180)
turtle.fd(40*2/3)
turtle.done()                  # 窗口实现不自动关闭
turtle.s

方法2

from turtle import *
setup(650,350,200,200)
penup()
fd(-250)                
pendown()
pensize(25)
pencolor("purple")
seth(-40)                 
for i in range(4):
    circle(40,80)
    circle(-40,80)
circle(40,80/2)
fd(40)
circle(16,180)
fd(40*2/3)
done()

方法3

import turtle as t
t.setup(650,350,200,200)
t.penup()
t.fd(-250)                 
t.pendown()
t.pensize(25)
t.pencolor("purple")
t.seth(-40)                 
for i in range(4):
    t.circle(40,80)
    t.circle(-40,80)
t.circle(40,80/2)
t.fd(40)
t.circle(16,180)
t.fd(40*2/3)
t.done()

   ### 习题18 五角星绘制

from turtle import *
color('black', 'red')
begin_fill()
for i in range(5):
    fd(200)
    rt(144)
end_fill()
done()

习题19 温度转换

#TempCovert.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("输入格式有误")
### 习题20 七段数码管绘制(plus)
#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() 

习题21 七段数码管绘制(时间)

#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('20201013')
 turtle.hideturtle()
 turtle.done()


main()

习题22 词云(不规则)

#GovRptWordCloudv2.py
import jieba
import wordcloud
from scipy.misc import imread
mask = imread("chinamap.jpg")
excludes = { }
f = open("新时代中国特色社会主义.txt", "r", encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud(\
    width = 1000, height = 700,\
    background_color = "white",
    font_path = "msyh.ttc", mask = mask
    )
w.generate(txt)
w.to_file("grwordcloudm.png")

习题23 词云(矩形)

#GovRptWordCloudv1.py
import jieba
import wordcloud

f = open("新时代中国特色社会主义.txt", "r", encoding="utf-8")

t = f.read()
f.close()
ls = jieba.lcut(t)

txt = " ".join(ls)
w = wordcloud.WordCloud( \
    width=1000, height=700, \
    background_color="white",
    font_path="msyh.ttc"
)
w.generate(txt)
w.to_file("grwordcloud.png")

习题24 给定一个单词,请使用凯撒密码将这个单词加密。凯撒密码是一种替换加密的技术,单词中的所有字母都在字母表上向后偏移3位后被替换成密文。即a变为d,b变为e,…,w变为z,x变为a,y变为b,z变为c。

例如,lanqiao会变成odqtldr。

s = input('请输入要加密的字符串:')
k = int(input('请输入移位值:'))
s_encrypt = ''
for word in s:
	if word == ' ':
		word_encrypt = ' '
	else:
		word_encrypt = chr((ord(word)-ord('a') + k) % 26 + ord('a'))   
	s_encrypt += word_encrypt
print(s_encrypt)

你可能感兴趣的:(Python,python,开发语言)