311 lines
12 KiB
Python
311 lines
12 KiB
Python
# ==============================================================================
|
||
# 通过 D:\文档\电子文档\个人\脚本库\PythonScript\第8章.py + 题号 运行
|
||
# 程序名:
|
||
# 第8章习题
|
||
# 目的:
|
||
#
|
||
# 修订记录:
|
||
# 日期 编程者 改动描述
|
||
# =================== ============= =====================================
|
||
# 2021-07-29 22:27:49 Sola 8-1 ~ 8-3 略
|
||
# 2021-07-29 22:31:50 Sola 8-4 Syracuse序列
|
||
# 2021-07-29 22:55:15 Sola 8-5 素数判断
|
||
# 2021-07-29 23:23:41 Sola 8-6 找出每一个素数
|
||
# 2021-07-30 19:13:22 Sola 8-7 哥德巴赫猜想
|
||
# 2021-07-30 19:21:14 Sola 8-8 最大公约数
|
||
# 2021-07-30 20:00:17 Sola 8-9 计算燃油效率
|
||
# 2021-07-30 20:00:28 Sola 8-10 从文件读入数据,计算燃油效率
|
||
# 2021-07-30 20:18:47 Sola 8-11 加热度天、制冷度天
|
||
# 2021-07-30 20:19:01 Sola 8-12 从文件读入计算加热度天、制冷度天
|
||
# 2021-07-30 20:21:57 Sola 8-13 回归线绘制
|
||
# 2021-07-30 21:01:56 Sola 8-14 图像转灰度并保存
|
||
# 2021-07-30 21:52:08 Sola 8-15 图形转补色并保存
|
||
# 2021-07-30 21:58:42 Sola 8-16 event_loop3,增加ESC退出文本框的功能
|
||
|
||
def Test8_4():
|
||
intNum = int(input("请输入一个正整数:"))
|
||
if intNum > 0:
|
||
while intNum != 1:
|
||
print("{0}, ".format(intNum), end="")
|
||
if intNum % 2 == 0:
|
||
intNum = intNum // 2
|
||
else:
|
||
intNum = 3 * intNum + 1
|
||
print(1)
|
||
else:
|
||
print("警告:输入值非法!")
|
||
|
||
def Test8_5():
|
||
def IsPrimeNum(intNum):
|
||
# 循环到底类型
|
||
result = True
|
||
if intNum > 1:
|
||
for i in range(2, intNum // 2 + 1):
|
||
if intNum % i == 0:
|
||
result = False
|
||
break
|
||
else:
|
||
print("警告:输入值非法!")
|
||
result = -1
|
||
return result
|
||
def IsPrimeNum1(intNum):
|
||
# 每次循环逐步优化
|
||
result = True
|
||
if intNum > 1:
|
||
i = 2
|
||
end = intNum
|
||
while i < end:
|
||
if intNum % i == 0:
|
||
result = False
|
||
break
|
||
else:
|
||
i = i + 1
|
||
end = intNum // i + 1
|
||
print("共进行{0}次运算".format(i))
|
||
else:
|
||
print("警告:输入值非法!")
|
||
result = -1
|
||
return result
|
||
def IsPrimeNum2(intNum):
|
||
# 根据原理直接限定最大循环次数
|
||
result = True
|
||
if intNum > 1:
|
||
for i in range(2, int(intNum ** 0.5) + 1):
|
||
if intNum % i == 0:
|
||
result = False
|
||
break
|
||
else:
|
||
print("警告:输入值非法!")
|
||
result = -1
|
||
return result
|
||
intNum = int(input("请输入一个大于1正整数:"))
|
||
if intNum > 1:
|
||
if IsPrimeNum2(intNum):
|
||
print("{0}是素数".format(intNum))
|
||
else:
|
||
print("{0}不是素数".format(intNum))
|
||
else:
|
||
print("警告:输入值非法!")
|
||
|
||
def IsPrimeNum(intNum):
|
||
# 根据原理直接限定最大循环次数
|
||
result = True
|
||
if intNum > 1:
|
||
for i in range(2, int(intNum ** 0.5) + 1):
|
||
if intNum % i == 0:
|
||
result = False
|
||
break
|
||
else:
|
||
print("警告:输入值非法!")
|
||
result = -1
|
||
return result
|
||
|
||
def Test8_6():
|
||
intNum = int(input("请输入一个正整数:"))
|
||
if int(intNum) > 1:
|
||
print("小于{0}的素数包括:".format(intNum), end='')
|
||
print("2", end='')
|
||
for i in range(3, intNum + 1):
|
||
if IsPrimeNum(i):
|
||
print(", {0}".format(i), end='')
|
||
print("\n")
|
||
else:
|
||
print("警告:输入值非法!")
|
||
|
||
def Test8_7():
|
||
inputNum = int(input("请输入一个偶数:"))
|
||
if inputNum % 2 == 0:
|
||
for i in range(2, inputNum // 2 + 1):
|
||
if IsPrimeNum(i) and IsPrimeNum(inputNum - i):
|
||
print("{0}和{1}是和为{2}的两个素数".format(i, inputNum - i, inputNum))
|
||
break
|
||
else:
|
||
print("警告:输入值非偶数!")
|
||
|
||
def Test8_8():
|
||
inputList = input("请输入两个正整数:").split(",")
|
||
m, n = int(inputList[0]), int(inputList[1])
|
||
while m != 0:
|
||
n, m = m, n % m
|
||
print("{0}和{1}的最大公约数是:{2}".format(int(inputList[0]), int(inputList[1]), n))
|
||
|
||
def Test8_9():
|
||
mileage = float(input("请输入开始时里程表的读数:"))
|
||
mileageOld = mileage
|
||
fuelSum = 0
|
||
while True:
|
||
temp = input("\n请输入当前的里程表读数和燃油使用量(空格分隔):")
|
||
if temp:
|
||
infoList = temp.split()
|
||
mileageNow, fuel = float(infoList[0]), float(infoList[1])
|
||
print("当前路段的燃油效率为{0:.3f}MPG".format((mileageNow - mileageOld) / fuel))
|
||
fuelSum = fuelSum + fuel
|
||
mileageOld = mileageNow
|
||
else:
|
||
print("\n总路段的燃油效率为{0:.3f}MPG".format((mileageOld - mileage) / fuelSum))
|
||
break
|
||
|
||
def Test8_10():
|
||
from tkinter.filedialog import askopenfilename
|
||
inputFile = open(askopenfilename())
|
||
mileage = float(inputFile.readline())
|
||
mileageOld = mileage
|
||
fuelSum = 0
|
||
while True:
|
||
temp = inputFile.readline()
|
||
if temp:
|
||
infoList = temp.split()
|
||
mileageNow, fuel = float(infoList[0]), float(infoList[1])
|
||
print("当前路段的燃油效率为{0:.3f}MPG".format((mileageNow - mileageOld) / fuel))
|
||
fuelSum = fuelSum + fuel
|
||
mileageOld = mileageNow
|
||
else:
|
||
print("总路段的燃油效率为{0:.3f}MPG".format((mileageOld - mileage) / fuelSum))
|
||
break
|
||
|
||
def Test8_11():
|
||
temperatureList = input("请输入平均温度序列:").split()
|
||
heatSum = 0
|
||
refrSum = 0
|
||
for i in temperatureList:
|
||
if float(i) > 80:
|
||
refrSum = refrSum + float(i) - 80
|
||
elif float(i) < 60:
|
||
heatSum = heatSum + 60 - float(i)
|
||
print("加热度天和制冷度天分别为:{0}, {1}".format(heatSum, refrSum))
|
||
|
||
def Test8_12():
|
||
from tkinter.filedialog import askopenfilename
|
||
temperatureList = open(askopenfilename()).readline().split()
|
||
heatSum = 0
|
||
refrSum = 0
|
||
for i in temperatureList:
|
||
if float(i) > 80:
|
||
refrSum = refrSum + float(i) - 80
|
||
elif float(i) < 60:
|
||
heatSum = heatSum + 60 - float(i)
|
||
print("加热度天和制冷度天分别为:{0}, {1}".format(heatSum, refrSum))
|
||
|
||
def Test8_13():
|
||
from graphics import Point, Line, Rectangle, Text, GraphWin
|
||
win = GraphWin("绘制回归线", 400, 400)
|
||
win.setCoords(0, 0, 400, 400)
|
||
doneButtom = Rectangle(Point(10, 10), Point(60, 30))
|
||
doneButtom.setFill("white")
|
||
doneButtom.setOutline("black")
|
||
doneButtom.draw(win)
|
||
doneText = Text(Point(35, 20), "Done")
|
||
doneText.draw(win)
|
||
i = 0
|
||
sumX, sumY, sumXY, sumX2 = 0, 0, 0, 0
|
||
while True:
|
||
pointTemp = win.getMouse()
|
||
pointTemp.setFill("red")
|
||
|
||
x, y = pointTemp.getX(), pointTemp.getY()
|
||
if abs(x - 35) <= 15 and abs(y - 20) <= 10:
|
||
if i >= 2:
|
||
doneButtom.undraw()
|
||
doneText.undraw()
|
||
averageX, averageY = sumX / i, sumY / i
|
||
if sumX2 - i * averageX ** 2 != 0:
|
||
m = (sumXY - i * averageX * averageY) / (sumX2 - i * averageX ** 2)
|
||
Line(Point(0, averageY + m * (0 - averageX)), Point(400, averageY + m * (400 - averageX))).draw(win)
|
||
else:
|
||
Line(Point(averageX, 0), Point(averageX, 400)).draw(win)
|
||
break
|
||
else:
|
||
print("点位太少了!")
|
||
else:
|
||
pointTemp.clone().draw(win)
|
||
i = i + 1
|
||
sumX, sumY, sumXY, sumX2 = sumX + x, sumY + y, sumXY + x * y, sumX2 + x ** 2
|
||
Text(Point(200, 20), "Click again to quit").draw(win)
|
||
win.getMouse()
|
||
|
||
def Test8_14():
|
||
from tkinter.filedialog import askopenfilename, asksaveasfilename
|
||
from graphics import Image, GraphWin, Point, color_rgb
|
||
imageDir = askopenfilename()
|
||
imageFile = Image(Point(0, 0), imageDir)
|
||
imageHeight, imageWidth = imageFile.getHeight(), imageFile.getWidth()
|
||
win = GraphWin("图片转灰度", width=imageWidth, height=imageHeight)
|
||
win.setCoords(-imageWidth / 2, -imageHeight / 2, imageWidth / 2, imageHeight / 2)
|
||
imageFile.draw(win)
|
||
size = imageHeight * imageWidth
|
||
for i in range(0, imageWidth):
|
||
for j in range(0, imageHeight):
|
||
r, g, b = imageFile.getPixel(i, j)
|
||
brightness = int(round(0.299 * r + 0.587 * g + 0.114 * b))
|
||
imageFile.setPixel(i, j, color_rgb(brightness, brightness, brightness))
|
||
print("\r进度:{0:6.2f}%".format((i * imageHeight + j) / size * 100), end='')
|
||
imageFile.save(asksaveasfilename())
|
||
win.getMouse()
|
||
|
||
def Test8_15():
|
||
from tkinter.filedialog import askopenfilename, asksaveasfilename
|
||
from graphics import Image, GraphWin, Point, color_rgb
|
||
imageDir = askopenfilename()
|
||
imageFile = Image(Point(0, 0), imageDir)
|
||
imageHeight, imageWidth = imageFile.getHeight(), imageFile.getWidth()
|
||
win = GraphWin("图片转灰度", width=imageWidth, height=imageHeight)
|
||
win.setCoords(-imageWidth / 2, -imageHeight / 2, imageWidth / 2, imageHeight / 2)
|
||
imageFile.draw(win)
|
||
size = imageHeight * imageWidth
|
||
for i in range(0, imageWidth):
|
||
for j in range(0, imageHeight):
|
||
r, g, b = imageFile.getPixel(i, j)
|
||
imageFile.setPixel(i, j, color_rgb(255 - r, 255 - g, 255 - b))
|
||
print("\r进度:{0:6.2f}%".format((i * imageHeight + j) / size * 100), end='')
|
||
imageFile.save(asksaveasfilename())
|
||
win.getMouse()
|
||
|
||
def Test8_16():
|
||
from graphics import GraphWin, Entry, Text
|
||
def handleKey(k, win):
|
||
if k == "r":
|
||
win.setBackground("pink")
|
||
elif k == "w":
|
||
win.setBackground("white")
|
||
elif k == "g":
|
||
win.setBackground("lightgray")
|
||
elif k == "b":
|
||
win.setBackground("lightblue")
|
||
|
||
def handleClick(pt, win):
|
||
# create an Entry for user to type in
|
||
entry = Entry(pt, 10)
|
||
entry.draw(win)
|
||
# Go modal: loop until user types <Enter> key
|
||
while True:
|
||
key = win.getKey()
|
||
if key == "Return":
|
||
entry.undraw()
|
||
typed = entry.getText()
|
||
Text(pt, typed).draw(win)
|
||
# clear (ignore) any mouse click that occurred during text entry
|
||
win.checkMouse()
|
||
break
|
||
if key == "Escape":
|
||
entry.undraw()
|
||
break
|
||
# undraw the entry and create and draw Text0
|
||
|
||
win = GraphWin("Click and Type", 500, 500)
|
||
# Event Loop: handle key presses and mouse clicks until the user
|
||
# presses the "q" key.
|
||
while True:
|
||
key = win.checkKey()
|
||
if key == "q": # loop exit
|
||
break
|
||
if key:
|
||
handleKey(key, win)
|
||
pt = win.checkMouse()
|
||
if pt:
|
||
handleClick(pt, win)
|
||
win.close()
|
||
|
||
import sys
|
||
def Run(num):
|
||
eval("Test8_" + num + "()")
|
||
Run(sys.argv[1]) |