From 7632e026e94d92c1fed76aecc98f1dcff124fe26 Mon Sep 17 00:00:00 2001 From: SolaSUSTech Date: Thu, 25 Sep 2025 21:23:34 +0800 Subject: [PATCH] init --- 20210720-第2章.py | 102 +++++++++++++++ 20210721-第3章.py | 149 ++++++++++++++++++++++ 20210721-第4章.py | 281 +++++++++++++++++++++++++++++++++++++++++ 20210723-第5章.py | 248 ++++++++++++++++++++++++++++++++++++ 20210726-第6章.py | 204 ++++++++++++++++++++++++++++++ 20210727-第7章.py | 143 +++++++++++++++++++++ 20210729-第8章.py | 311 ++++++++++++++++++++++++++++++++++++++++++++++ 20210801-第9章.py | 293 +++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 1731 insertions(+) create mode 100644 20210720-第2章.py create mode 100644 20210721-第3章.py create mode 100644 20210721-第4章.py create mode 100644 20210723-第5章.py create mode 100644 20210726-第6章.py create mode 100644 20210727-第7章.py create mode 100644 20210729-第8章.py create mode 100644 20210801-第9章.py diff --git a/20210720-第2章.py b/20210720-第2章.py new file mode 100644 index 0000000..ea33c62 --- /dev/null +++ b/20210720-第2章.py @@ -0,0 +1,102 @@ +# ============================================================================== +# 通过 D:\文档\电子文档\个人\脚本库\PythonScript\第2章.py + 题号 运行 +# 程序名: +# 第2章习题 +# 目的: +# +# 修订记录: +# 日期 编程者 改动描述 +# =================== ============= ===================================== +# 2021-07-20 21:29:18 Sola 2-1 介绍呗 +# 2021-07-20 21:29:30 Sola 2-2 介绍完不自动退出 +# 2021-07-20 21:29:42 Sola 2-3 计算平均分 +# 2021-07-20 21:29:54 Sola 2-4 计算5次华氏度 +# 2021-07-20 21:30:22 Sola 2-5 计算0~100℃对应华氏度 +# 2021-07-20 21:30:47 Sola 2-6 本金利滚利 +# 2021-07-20 21:31:11 Sola 2-7 追加利滚利 +# 2021-07-20 21:31:21 Sola 2-8 利滚利滚利(我是有极限的!) +# 2021-07-20 21:35:18 Sola 2-9 华氏度转摄氏度 +# 2021-07-20 21:38:07 Sola 2-10 千米转英里 +# 2021-07-20 21:42:45 Sola 2-11 任意一个单位转换 略 +# 2021-07-20 21:42:59 Sola 2-12 Python计算器 + +def test2_1(): + print("Hello, World! 这里我就懒得再改介绍了,怪麻烦的。") + +def test2_2(): + print("Hello, World! 这里我就懒得再改介绍了,怪麻烦的。") + input("Press the key to quit.") + +def test2_3(): + print("This program computes the average of two exam scores.") + score1, score2, score3 = eval(input("Enter three scores separated by a comma: ")) + average = (score1 + score2 + score3) / 3 + print("The average of the scores is:", average) + +def test2_4(): + for i in range(5): + celsius = eval(input("What is the Celsius temperature? ")) + fahrenheit = 9/5 * celsius + 32 + print("The temperature is", fahrenheit, "degrees Fahrenheit.") + +def test2_5(): + celsius = 0 + print("摄氏度(℃)\t华氏度(℉)") + for i in range(11): + fahrenheit = 9/5 * celsius + 32 + print('', celsius, "\t\t", fahrenheit) + celsius = celsius + 10 + +def test2_6(): + print("This program calculates the future value of a investment.") + principal = eval(input("Enter the initial principal: ")) + years = eval(input("Enter the number of years of your investment: ")) + apr = eval(input("Enter the annual interest rate: ")) + for i in range(years): + principal = principal * (1 + apr) + print("The value in", years, "years is:", principal) + +def test2_7(): + print("This program calculates the future value of a investment.") + investment = eval(input("Enter the annual investment: ")) + years = eval(input("Enter the number of years of your investment: ")) + apr = eval(input("Enter the annual interest rate: ")) + principal = investment + for i in range(years): + principal = principal * (1 + apr) + investment + print("The value in", years, "years is:", principal) + +def test2_8(): + print("This program calculates the future value of a investment.") + principal = eval(input("Enter the initial principal: ")) + years = eval(input("Enter the number of years of your investment: ")) + times = eval(input("Enter the number of interest calculations per year: ")) + apr = eval(input("Enter the annual interest rate: ")) + for i in range(years): + for j in range(times): + principal = principal * (1 + apr / times) + print("The value in", years, "years is:", principal) + +def test2_9(): + fahrenheit = eval(input("What is the Fahrenheit temperature? ")) + celsius = 5/9 * ( fahrenheit - 32 ) + print("The temperature is", celsius, "degrees celsius.") + +def test2_10(): + km = eval(input("请输入千米数: ")) + print(km, "km =", 0.62 * km, "mile") + +def test2_11(): + print("太简单,略过,,,实在懒得再重写一个了") + +def test2_12(): + print("Python 交互式科学计算器") + for i in range(100): + expr = input("请输入算数表达式:") + a = eval(expr) + print(expr, "的结果为", a, ",您还可以计算", 99 - i, "次") + +import sys +def run(num): + eval("test2_" + num + "()") +run(sys.argv[1]) \ No newline at end of file diff --git a/20210721-第3章.py b/20210721-第3章.py new file mode 100644 index 0000000..31d06ce --- /dev/null +++ b/20210721-第3章.py @@ -0,0 +1,149 @@ +# ============================================================================== +# 通过 D:\文档\电子文档\个人\脚本库\PythonScript\第3章.py + 题号 运行 +# 程序名: +# 第3章习题 +# 目的: +# +# 修订记录: +# 日期 编程者 改动描述 +# =================== ============= ===================================== +# 2021-07-21 02:48:55 Sola 3-1 计算球体表面积和体积 +# 2021-07-21 02:49:12 Sola 3-2 计算比萨饼单价 +# 2021-07-21 02:49:22 Sola 3-3 计算分子中碳水化合物的分子量 +# 2021-07-21 02:54:30 Sola 3-4 计算雷击距离 +# 2021-07-21 03:04:14 Sola 3-5 计算咖啡订单费用 +# 2021-07-21 03:04:28 Sola 3-6 计算两点间斜率 +# 2021-07-21 03:04:36 Sola 3-7 计算两点间距离 +# 2021-07-21 03:20:35 Sola 3-8 计算格里高利闰余 +# 2021-07-21 12:33:33 Sola 3-9 三角形面积 +# 2021-07-21 12:33:49 Sola 3-10 计算梯子所需长度 +# 2021-07-21 12:40:27 Sola 3-11 计算前n个自然数的和 +# 2021-07-21 12:48:14 Sola 3-12 计算前n个自然数的立方和 +# 2021-07-21 12:48:32 Sola 3-13 计算输入指定个数数字的和 +# 2021-07-21 12:49:24 Sola 3-14 计算输入指定个数数字的平均值 +# 2021-07-21 12:51:11 Sola 3-15 级数各项求和 +# 2021-07-21 14:41:27 Sola 3-16 斐波那契数列计算 +# 2021-07-21 14:41:38 Sola 3-17 平方根算法 +# module start +import math +pi = 3.14159265 +# module end + +def test3_1(): + r = float(input("请输入球体的半径: ")) + V = 4 / 3 * pi * r ** 3 + A = 4 * pi * r ** 2 + print("球体的体积为:", V, "\n球体的表面积为:", A) + +def test3_2(): + r = float(input("请输入圆形比萨饼的直径:")) + prise = float(input("请输入圆形比萨饼的价格:")) + unitPrise = prise / (4 * pi * r ** 2) + print("比萨饼的单位面积价格为:", unitPrise) + +def test3_3(): + numH = int(input("请输入分子中H原子数量:")) + numC = int(input("请输入分子中C原子数量:")) + numO = int(input("请输入分子中O原子数量:")) + print("一摩尔该物质中存在碳水化合物的总量为", numH * 1.00794 + numC * 12.0107 + numO * 15.9994, "克") + +def test3_4(): + time = float(input("请输入闪光和雷声之间的时间差(秒):")) + print("雷击发生在距离大约", time * 1100 / 5280, "英里处") + +def test3_5(): + weight = float(input("请输入咖啡的重量(磅):")) + print("该订单费用为 $", weight * (0.86 + 10.50) + 1.50 ) + +def test3_6(): + x1, y1 = eval(input("请输入坐标(x1, y1):")) + x2, y2 = eval(input("请输入坐标(x2, y2):")) + print("(x1, y1) 与 (x2, y2) 之间的斜率为:", (y2 - y1)/(x2 - x1)) + +def test3_7(): + x1, y1 = eval(input("请输入坐标(x1, y1):")) + x2, y2 = eval(input("请输入坐标(x2, y2):")) + print("(x1, y1) 与 (x2, y2) 之间的距离为:", math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)) + +def test3_8(): + year = int(input("请输入一个4位数年份:")) + C = year // 100 + epact = (8 + (C // 4) - C + ((8 * C + 13) // 25) + 11 * (year % 19)) % 30 + print(year, "年的格里高利闰余为", epact) + +def test3_9(): + a, b, c = eval(input("请分别输入三角形三边长a, b, c:")) + s = (a + b + c) / 2 + A = math.sqrt(s * (s - a) * (s - b) * (s - c)) + print("三角形的面积为:", A) + +def test3_10(): + height = float(input("请输入梯子需要达到的高度 (m):")) + degree = float(input("请输入梯子的倾斜角度 (°):")) + rad = pi / 180 * degree + length = height / math.sin(rad) + print("梯子所需的长度为", length, "m") + +def test3_11(): + n = int(input("请输入需要计算的数字个数:")) + sum = 0 + for i in range(n): + sum = sum + i + print("前", n, "个自然数的和为", sum) + +def test3_12(): + n = int(input("请输入需要计算的数字个数:")) + sum = 0 + for i in range(n): + sum = sum + i ** 3 + print("前", n, "个自然数的立方和为", sum) + +def test3_13(): + n = int(input("请输入需要计算的数字个数:")) + sum = 0 + for i in range(n): + print("请输入需要求和的第", i + 1, "个数:", end='') + num = float(input()) + sum = sum + num + print("所有输入的数字的和为", sum) + +def test3_14(): + n = int(input("请输入需要计算的数字个数:")) + sum = 0 + for i in range(n): + print("请输入需要求均值的第", i + 1, "个数:", end='') + num = float(input()) + sum = sum + num + average = sum / (n + 1) + print("所有输入的数字的平均值为", average) + +def test3_15(): + n = int(input("请输入需要求和的项数:")) + sum = 0 + for i in range(n): + sum = sum + (-1) ** i * 4 / (2 * i + 1) + distance = math.pi - sum + print("计算得到的近似PI值为:", sum) + print("与真实PI之间的差为:", distance) + +def test3_16(): + n = int(input("请输入需要计算的斐波那契数列项数(正整数):")) + temp = 0 + result = 1 + for i in range(n - 1): + temp, result = result, temp + result + print("斐波那契数列第", n, "项为:", result) + +def test3_17(): + num = float(input("请输入需要求取平方根的数:")) + times = int(input("请输入牛顿法迭代次数:")) + result = num / 2 + for i in range(times): + result = (result + num / result) / 2 + print("所求", num, "的平方根为:", result) + print("所求", num, "的平方根与真实值的差距为:", math.sqrt(num) - result) + +import sys +def run(num): + eval("test3_" + num + "()") +run(sys.argv[1]) \ No newline at end of file diff --git a/20210721-第4章.py b/20210721-第4章.py new file mode 100644 index 0000000..74d4490 --- /dev/null +++ b/20210721-第4章.py @@ -0,0 +1,281 @@ +# ============================================================================== +# 通过 D:\文档\电子文档\个人\脚本库\PythonScript\第4章.py + 题号 运行 +# 程序名: +# 第4章习题 +# 目的: +# +# 修订记录: +# 日期 编程者 改动描述 +# =================== ============= ===================================== +# 2021-07-21 17:28:01 Sola 4-a 计算终值的例题 +# 2021-07-21 17:28:24 Sola 4-b 通过获取三个点绘制三角形的例题 +# 2021-07-21 21:53:31 Sola 4-c 击键输入 +# 2021-07-21 21:53:54 Sola 4-d 点击移动圆形 +# 2021-07-21 21:54:11 Sola 4-1 点击生成正方形 +# 2021-07-21 21:54:27 Sola 4-2 生成靶标 +# 2021-07-21 22:05:13 Sola 4-3 绘制某种面孔。。。 +# 2021-07-21 22:08:23 Sola 4-4 ~ 4-5 略 +# 2021-07-21 22:08:35 Sola 4-6 通过Entry输入求终值 +# 2021-07-22 00:46:54 Sola 4-7 圆的交点 +# 2021-07-22 01:16:26 Sola 4-8 绘制线段并显示相关信息 +# 2021-07-22 01:29:07 Sola 4-9 绘制矩形并显示相关信息 +# 2021-07-22 01:33:57 Sola 4-10 绘制三角形并显示相关信息 +# 2021-07-22 01:59:03 Sola 4-11 绘制小房子 +# +# module start +from typing import Sequence +from graphics import * + +def test4_a(): + # Introduction + print("This program plots the growth of a 10-year investment.") + # Get principal and interest rate + principal = float(input("Enter the initial principal: ")) + apr = float(input("Enter the annualized interest rate: ")) + # Create a graphics window with labels on left edge + win = GraphWin("Investment Growth Chart", 320, 240) + win.setBackground("white") + Text(Point(20, 230), ' 0.0K').draw(win) + Text(Point(20, 180), ' 2.5K').draw(win) + Text(Point(20, 130), ' 5.0K').draw(win) + Text(Point(20, 80), ' 7.5K').draw(win) + Text(Point(20, 30), '10.0K').draw(win) + # Draw bar for initial principal + height = principal * 0.02 + bar = Rectangle(Point(40, 230), Point(65, 230-height)) + bar.setFill("green") + bar.setWidth(2) + bar.draw(win) + # Draw bars for successive years + for year in range(1,11): + # calculate value for the next year + principal = principal * (1 + apr) + # draw bar for this value + xll = year * 25 + 40 + height = principal * 0.02 + bar = Rectangle(Point(xll, 230), Point(xll+25, 230-height)) # 创建柱体 + bar.setFill("green") # 设置填充色 + bar.setWidth(2) # 设置轮廓宽度 + bar.draw(win) # 绘制 + input("Press to quit") + win.close() + +def test4_b(): + win = GraphWin("Draw a Triangle") + win.setCoords(0.0, 0.0, 10.0, 10.0) + message = Text(Point(5, 0.5), "Click on three points") + message.draw(win) + # Get and draw three vertices of triangle + p1 = win.getMouse() + p1.draw(win) + p2 = win.getMouse() + p2.draw(win) + p3 = win.getMouse() + p3.draw(win) + # Use Polygon object to draw the triangle + triangle = Polygon(p1,p2,p3) + triangle.setFill("peachpuff") + triangle.setOutline("cyan") + triangle.draw(win) + # Wait for another click to exit + message.setText("Click anywhere to quit.") + win.getMouse() + +def test4_c(): + win = GraphWin("Click and Type", 400, 400) + for i in range(10): + pt = win.getMouse() + key = win.getKey() + label = Text(pt, key) + label.draw(win) + +def test4_d(): + win = GraphWin() + shape = Circle(Point(50, 50), 20) + shape.setOutline("red") + shape.setFill("red") + shape.draw(win) + for i in range(10): + p = win.getMouse() + c = shape.getCenter() + dx = p.getX() - c.getX() + dy = p.getY() - c.getY() + shape.move(dx,dy) + win.close() + +def test4_1(): + win = GraphWin() + shape = Rectangle(Point(50, 50), Point(70, 70)) + shape.setOutline("red") + shape.setFill("red") + shape.draw(win) + for i in range(10): + p = win.getMouse() + c = shape.getCenter() + dx = p.getX() - c.getX() + dy = p.getY() - c.getY() + shape.clone().draw(win) + shape.move(dx,dy) + Text(Point(100, 180), "Click again to quit").draw(win) + win.getMouse() + win.close() + +def test4_2(): + win = GraphWin() + def draw_circle(r, s_fill): + shape = Circle(Point(100, 90), r) + shape.setFill(s_fill) + shape.setOutline("black") + shape.clone().draw(win) + draw_circle(75, "white") + draw_circle(60, "black") + draw_circle(45, "blue") + draw_circle(30, "red") + draw_circle(15, "yellow") + Text(Point(100, 180), "Click again to quit").draw(win) + win.getMouse() + win.close() + +def test4_3(): + win = GraphWin() + Text(Point(100, 90), "某种面孔").draw(win) + Text(Point(100, 180), "Click again to quit").draw(win) + win.getMouse() + win.close() + +def test4_6(): + win = GraphWin("Input menu", 400, 130) + Text(Point(200, 10), "This program plots the growth of a 10-year investment.").draw(win) + Text(Point(200, 30), "Enter the initial principal:").draw(win) + Text(Point(200, 70), "Enter the annualized interest rate:").draw(win) + apr_entry = Entry(Point(200, 90), 10) + apr_entry.draw(win) + principal_entry = Entry(Point(200, 50), 10) + principal_entry.draw(win) + Text(Point(200, 115), "Click again to continue").draw(win) + win.getMouse() + principal = float(principal_entry.getText()) + apr = float(apr_entry.getText()) + win = GraphWin("Investment Growth Chart", 320, 240) + win.setBackground("white") + Text(Point(20, 230), ' 0.0K').draw(win) + Text(Point(20, 180), ' 2.5K').draw(win) + Text(Point(20, 130), ' 5.0K').draw(win) + Text(Point(20, 80), ' 7.5K').draw(win) + Text(Point(20, 30), '10.0K').draw(win) + # Draw bar for initial principal + height = principal * 0.02 + bar = Rectangle(Point(40, 230), Point(65, 230-height)) + bar.setFill("green") + bar.setWidth(2) + bar.draw(win) + # Draw bars for successive years + for year in range(1,11): + # calculate value for the next year + principal = principal * (1 + apr) + # draw bar for this value + xll = year * 25 + 40 + height = principal * 0.02 + bar = Rectangle(Point(xll, 230), Point(xll+25, 230-height)) # 创建柱体 + bar.setFill("green") # 设置填充色 + bar.setWidth(2) # 设置轮廓宽度 + bar.draw(win) # 绘制 + win.getMouse() + +def test4_7(): + r = float(input("请输入圆的半径:")) + b = float(input("请属于水平线在y轴方向截距:")) + win = GraphWin() + win.setCoords(-10, -10, 10, 10) + Circle(Point(0, 0), r).draw(win) + Line(Point(-10, b), Point(10, b)).draw(win) + if abs(b) > r: + print("没有交点!") + else: + x = round((r ** 2 - b ** 2) ** 0.5, 1) + b = round(b, 1) + def printPoint(x, b): + p = Point(x, b) + p.setFill("red") + p.clone().draw(win) + Text(Point(x, b + 1), "(" + str(x) + ", " + str(b) + ")").draw(win) + printPoint(x, b) + printPoint(-x, b) + Text(Point(0, -9), "Click again to quit").draw(win) + win.getMouse() + +def test4_8(): + win = GraphWin() + text = Text(Point(100, 190), "请点击两个位置!") + text.draw(win) + p1 = win.getMouse() + p2 = win.getMouse() + l1 = Line(p1, p2) + l1.draw(win) + p3 = l1.getCenter() + p3.setFill("blue") + p3.draw + if (p2.getX() - p1.getX()) == 0: + slope = "inf" + else: + slope = round((p2.getY() - p1.getY()) / (p2.getX() - p1.getX()), 4) + length = round(((p2.getY() - p1.getY()) ** 2 + (p2.getX() - p1.getX()) ** 2) ** 0.5, 4) + print("线段的斜率为:", slope) + print("线段的长度为:", length) + text.setText("Click again to quit") + win.getMouse() + +def test4_9(): + win = GraphWin() + text = Text(Point(100, 190), "请点击两个位置!") + text.draw(win) + p1 = win.getMouse() + p2 = win.getMouse() + l1 = Rectangle(p1, p2) + l1.draw(win) + cRectangle = round((abs(p2.getY() - p1.getY()) + abs(p2.getX() - p1.getX())) * 2, 4) + sRectangle = round(abs(p2.getY() - p1.getY()) * abs(p2.getX() - p1.getX()), 4) + print("矩形的周长为:", cRectangle) + print("矩形的面积为:", sRectangle) + text.setText("Click again to quit") + win.getMouse() + +def test4_10(): + win = GraphWin() + text = Text(Point(100, 190), "请点击三个位置!") + text.draw(win) + p1 = win.getMouse() + p2 = win.getMouse() + p3 = win.getMouse() + Polygon(p1, p2, p3).draw(win) + a = ((p2.getY() - p1.getY()) ** 2 + (p2.getX() - p1.getX()) ** 2) ** 0.5 + b = ((p3.getY() - p2.getY()) ** 2 + (p3.getX() - p2.getX()) ** 2) ** 0.5 + c = ((p3.getY() - p1.getY()) ** 2 + (p3.getX() - p1.getX()) ** 2) ** 0.5 + cPolygon = round(a + b + c, 4) + sPolygon = round((cPolygon / 2 * (cPolygon / 2 - a) * (cPolygon / 2 - b) * (cPolygon / 2 - c)) ** 0.5, 4) + print("三角形的周长为:", cPolygon) + print("三角形的面积为:", sPolygon) + text.setText("Click again to quit") + win.getMouse() + +def test4_11(): + win = GraphWin() + text = Text(Point(100, 190), "请点击五个位置!") + text.draw(win) + p1 = win.getMouse() + p2 = win.getMouse() + p3 = win.getMouse() + p4 = win.getMouse() + p5 = win.getMouse() + d = p2.getX() - p1.getX() + Rectangle(p1, p2).draw(win) + Polygon(p2, Point(p1.getX(), p2.getY()), p5).draw(win) + Rectangle(Point(p3.getX() + d * 0.1, p3.getY()), Point(p3.getX() - d * 0.1, p1.getY())).draw(win) + Rectangle(Point(p4.getX() + d * 0.05, p4.getY() + d * 0.05), Point(p4.getX() - d * 0.05, p4.getY() - d * 0.05)).draw(win) + text.setText("Click again to quit") + win.getMouse() + +import sys +def run(num): + eval("test4_" + num + "()") +run(sys.argv[1]) \ No newline at end of file diff --git a/20210723-第5章.py b/20210723-第5章.py new file mode 100644 index 0000000..0d6fdd8 --- /dev/null +++ b/20210723-第5章.py @@ -0,0 +1,248 @@ +# ============================================================================== +# 通过 D:\文档\电子文档\个人\脚本库\PythonScript\第5章.py + 题号 运行 +# 程序名: +# 第5章习题 +# 目的: +# +# 修订记录: +# 日期 编程者 改动描述 +# =================== ============= ===================================== +# 2021-07-23 15:52:52 Sola 5-1 简化dateconvert2,格式化时间输出 +# 2021-07-23 15:57:01 Sola 5-2 分数等级转化 +# 2021-07-23 16:29:47 Sola 5-3 百分制分数等级转化 +# 2021-07-23 16:30:00 Sola 5-4 获取短语缩写 +# 2021-07-23 16:44:47 Sola 5-5 计算输入单个名字的数值 +# 2021-07-23 16:49:19 Sola 5-6 计算所有名字的数字之和 +# 2021-07-23 17:02:26 Sola 5-7 简单基于Unicode的凯撒密码 +# 2021-07-23 17:15:16 Sola 5-8 真正的凯撒密码 +# 2021-07-23 17:53:11 Sola 5-9 计算用户输入句子的单词数 +# 2021-07-23 21:59:33 Sola 5-10 计算输入句子中单词的平均长度 +# 2021-07-23 22:04:15 Sola 5-11 第1章 chaos.py 改进版本 +# 2021-07-23 22:22:38 Sola 5-12 第二章算终值改进版本 +# 2021-07-23 22:23:03 Sola 5-13 ? +# 2021-07-23 22:23:15 Sola 5-14 统计文件的行数、单词数和字符数 +# 2021-07-23 23:21:10 Sola 5-15 学生成绩统计表 +# 2021-07-23 23:21:28 Sola 5-16 数字频数统计表 +# +# module start +# from graphics import * # 引入图形库 + +from os import times + + +def test5_1(): + # get the date + dateStr = input("Enter a date (mm/dd/yyyy): ") + # split into components + monthStr, dayStr, yearStr = dateStr.split("/") + # convert monthStr to the month name + months = ["January", "February", "March", "April", + "May", "June", "July", "August", + "September", "October", "November", "December"] + monthStr = months[int(monthStr)-1] + # output result in month day, year format + print("The converted date is: {0} {1}, {2}".format(monthStr, dayStr, yearStr)) + +def test5_2(): + score = int(input("请输入你的分数:")) + grade = ["F", "E", "D", "C", "B", "A"] + result = grade[score] + print("你的分数对应的等级为:{0}".format(result)) + +def test5_3(): + score = int(float(input("请输入你的分数:")) / 10) + grade = ["F", "F", "F", "F", "F", "F", "D", "C", "B", "A", "A"] + result = grade[score] + print("你的分数对应的等级为:{0}".format(result)) + +def test5_4(): + inputStr = input("请输入一个短语:") + shortName = "" + for i in inputStr.split(): + shortName = shortName + i[0].upper() + print("'{0}' 的缩写为:{1}".format(inputStr, shortName)) + +def test5_5(): + name = input("请输入单个名字:").lower() + sum = 0 + for i in name: + sum = sum + ord(i) - 96 + print("{0} 的数值为:{1}".format(name, sum)) + +def test5_6(): + name = input("请输入你的名字:").lower() + sum = 0 + for i in name.split(): + for j in i: + sum = sum + ord(j) - 96 + print("{0} 的数值为:{1}".format(name, sum)) + +def test5_7(): + char = input("请输入需要加密的密文:") + key = int(input("请输入密文的偏移位数:")) + def code(char, key): + coding = "" + for ch in char: + coding = coding + chr(ord(ch) + key) + return coding + coding = code(char, key) + print("{0} 编码后的密文为:{1}".format(char, coding)) + key = int(input("请输入密钥:")) + decoding = code(coding, -key) + print("{0} 解码后的明文为:{1}".format(coding, decoding)) + +def test5_8(): + char = input("请输入需要加密的密文:") + key = int(input("请输入密文的偏移位数:")) + def code(char, key): + keyList = "abcdefghijklmnopqrstuvwxyz" + coding = "" + for ch in char: + if ord(ch) <= ord("z") and ord(ch) >= ord("a"): + coding = coding + keyList[(ord(ch) + key - ord("a")) % 26] + elif ord(ch) <= ord("Z") and ord(ch) >= ord("A"): + coding = coding + keyList[(ord(ch) + key - ord("A")) % 26].upper() + else: + coding = coding + ch + return coding + coding = code(char, key) + print("{0} 编码后的密文为:{1}".format(char, coding)) + key = int(input("请输入密钥:")) + decoding = code(coding, -key) + print("{0} 解码后的明文为:{1}".format(coding, decoding)) + +def test5_9(): + inputSentence = input("请输入需要统计的句子:") + num = 0 + for ch in inputSentence.title(): + if ord(ch) <= ord("Z") and ord(ch) >= ord("A"): + num = num + 1 + print("输入语句 {0} 中有 {1} 个单词".format(inputSentence, num)) + +def test5_10(): + inputSentence = input("请输入需要统计的句子:") + num = 0 + long = 0 + for ch in inputSentence.title(): + if ord(ch) <= ord("Z") and ord(ch) >= ord("A"): + num = num + 1 + for ch in inputSentence.lower(): + if ord(ch) <= ord("z") and ord(ch) >= ord("a"): + long = long + 1 + print("输入语句 {0} 中每个单词的平均长度为 {1:2.1f}".format(inputSentence, long / num)) + +def test5_11(): + inputList = input("请输入两个初始值(用逗号分隔):").split(",") + init1, init2 = float(inputList[0]), float(inputList[1]) + times = int(input("请输入迭代次数:")) + print("index {0:^8.2f} {1:^8.2f}\n------------------------------".format(init1, init2)) + for i in range(times): + init1 = 3.9 * init1 * (1 - init1) + init2 = 3.9 * init2 * (1 - init2) + print("{0:<5} {1:8.6f} {2:8.6f}".format(int(i) + 1, init1, init2)) + +def test5_12(): + print("This program calculates the future value of a investment.") + principal = eval(input("Enter the principal: ")) + years = eval(input("Enter the number of years of your investment: ")) + apr = eval(input("Enter the annual interest rate: ")) + print("Year {0:^8}\n----------------".format("Value")) + print("{0:<4} ${1:>7.2f}".format(0, principal)) + for i in range(years): + principal = principal * (1 + apr) + print("{0:<4} ${1:>7.2f}".format(i + 1, principal)) + +def test5_13(): + print("???不玩了不玩了,没意思,再见吧您嘞!") + +def test5_14(): + from tkinter.filedialog import askopenfilename + print("请选择需要统计的文件:") + inputFileName = askopenfilename() + inputFile = open(inputFileName, 'r') + print("成功打开文件:{0}".format(inputFileName)) + numLines = len(inputFile.readlines()) + print("文件中共有句子 {0} 行".format(numLines)) + numWords = 0 + numChs = 0 + inputFile = open(inputFileName, 'r') + for ch in inputFile.read().title(): + if ord(ch) <= ord("Z") and ord(ch) >= ord("A"): + numWords = numWords + 1 + numChs = numChs + 1 + print("文件中共有单词 {0} 个".format(numWords)) + print("文件中共有字符 {0} 个".format(numChs)) + +def test5_15(): + # 4 + # Computewell, 90 + # Dibblebit, 60 + # Jones, 80 + # Smith, 70 + from tkinter.filedialog import askopenfilename + from graphics import GraphWin, Text, Rectangle, Point + print("请选择输入的文件记录:") + inputFile = open(askopenfilename(), 'r') + print("成功打开文件!") + numStudents = int(inputFile.readline()) + win = GraphWin("学生考试成绩", 800, numStudents * 30) + for i in range(numStudents): + infoList = inputFile.readline().split(",") + Text(Point(95, 15 + 30 * i), infoList[0]).draw(win) + Rectangle(Point(200, 7 + 30 * i), Point(200 + 590 * float(infoList[1]) / 100, 23 + 30 * i)).draw(win) + win.getMouse() + +def test5_16(): + # 0 + # 1 + # 2 + # 2 + # 4 + # 4 + # 4 + # 5 + # 5 + # 5 + # 5 + # 6 + # 6 + # 6 + # 6 + # 6 + # 7 + # 7 + # 7 + # 7 + # 7 + # 7 + # 7 + # 8 + # 8 + # 8 + # 9 + # 9 + # 9 + # 10 + # 10 + from tkinter.filedialog import askopenfilename + from graphics import GraphWin, Text, Rectangle, Point + print("请选择输入的文件记录:") + numList = open(askopenfilename(), 'r').readlines() + print("成功打开文件!") + timesList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + for i in numList: + timesList[int(i)] = timesList[int(i)] + 1 + win = GraphWin("数字统计", 440, 300) + numMax = max(timesList) + num = 0 + for i in timesList: + Text(Point(20 + 40 * num, 285), num).draw(win) + Rectangle(Point(10 + 40 * num, 270), Point(30 + 40 * num, 270 - 260 * i / numMax)).draw(win) + num = num + 1 + win.getMouse() + + +import sys +def run(num): + eval("test5_" + num + "()") +run(sys.argv[1]) \ No newline at end of file diff --git a/20210726-第6章.py b/20210726-第6章.py new file mode 100644 index 0000000..196c3c1 --- /dev/null +++ b/20210726-第6章.py @@ -0,0 +1,204 @@ +# ============================================================================== +# 通过 D:\文档\电子文档\个人\脚本库\PythonScript\第6章.py + 题号 运行 +# 程序名: +# 第6章习题 +# 目的: +# +# 修订记录: +# 日期 编程者 改动描述 +# =================== ============= ===================================== +# 2021-07-26 13:52:58 Sola 6-1 打印歌曲“Old MacDonald”的歌词 +# 2021-07-26 16:21:07 Sola 6-2 略 +# 2021-07-26 16:21:16 Sola 6-3 给定球体半径,求表面积和体积 +# 2021-07-26 16:28:27 Sola 6-4 计算前N个自然数的和、立方和 +# 2021-07-26 16:35:53 Sola 6-5 披萨饼单价 +# 2021-07-26 18:32:19 Sola 6-6 三角形面积 +# 2021-07-26 18:32:42 Sola 6-7 斐波纳契数 +# 2021-07-26 18:35:29 Sola 6-8 平方根估计 +# 2021-07-26 18:42:07 Sola 6-9 返回分数字母等级 +# 2021-07-26 18:47:48 Sola 6-10 返回首字母缩略词 +# 2021-07-26 18:55:52 Sola 6-11 返回列表数字平方 +# 2021-07-26 21:42:06 Sola 6-12 返回数字列表的和 +# 2021-07-26 18:56:18 Sola 6-13 将字符串列表转化为数字 +# 2021-07-26 21:44:27 Sola 6-14 从文件读取数字计算平方和 +# 2021-07-27 00:52:48 Sola 6-15 显示简单笑脸 +# 2021-07-27 00:53:05 Sola 6-16 给图片点选加笑脸 +# 2021-07-27 00:53:21 Sola 6-17 移动图形到点选位置 + +from graphics import GraphWin + +def test6_1(): + def print_Old_MacDonald(animal, barking): + print("Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!\n" + + "And on that farm he had a {0}, Ee-igh, Ee-igh, Oh!\n".format(animal) + + "With a {0}, {0} here and a {0}, {0} there.\n".format(barking) + + "Here a {0}, there a {0}, everywhere a {0}, {0}.\n".format(barking) + + "Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!\n") + print_Old_MacDonald("bee", "buzz") + print_Old_MacDonald("bird", "tweet") + print_Old_MacDonald("cat", "meow") + print_Old_MacDonald("hen", "cluck") + print_Old_MacDonald("cuckoo", "cuckoo") + +def test6_3(): + from math import pi + def sphereArea(radius): + return 4 * pi * radius ** 2 + def sphereVolume(radius): + return 4 / 3 * pi * radius ** 3 + radius=1 + print("半径为{0}的球体,其表面积为{1:5.3f},体积为{2:5.3f}" + .format(radius, sphereArea(radius), sphereVolume(radius))) + +def test6_4(): + def sumN(n): + result = 0 + for i in range(n + 1): + result = result + i + return result + def sumNCubes(n): + result = 0 + for i in range(n + 1): + result = result + i ** 3 + return result + n = 10 + print("前{0}位自然数的和为{1},立方和为{2}" + .format(n, sumN(n), sumNCubes(n))) + +def test6_5(): + def pizzaUnitPrise(r, prise): + from math import pi + return prise / (4 * pi * r ** 2) + +def test6_6(): + def triangleArea(a, b, c): + from math import sqrt + s = (a + b + c) / 2 + return sqrt(s * (s - a) * (s - b) * (s - c)) + +def test6_7(): + def Fibonacci(n): + temp = 0 + result = 1 + for i in range(n - 1): + temp, result = result, temp + result + return result + print("斐波那契数列第", 10, "项为:", Fibonacci(10)) + +def test6_8(): + def nextGuess(guess,x): + result = guess / 2 + for i in range(x): + result = (result + guess / result) / 2 + return result + print("{0}的平方根迭代{1}次的估计值为{2:5.3f}".format(10, 10, nextGuess(10, 10))) + +def test6_9(): + def grade(score): + grade = ["F", "F", "F", "F", "F", "F", "D", "C", "B", "A", "A"] + return grade[int(score / 10)] + score = float(input("请输入你的分数:")) + print("你的分数对应的等级为:{0}".format(grade(score))) + +def test6_10(): + def acronym(phrase): + shortName = "" + for i in phrase.split(): + shortName = shortName + i[0].upper() + return shortName + inputStr = input("请输入一个短语:") + print("'{0}' 的缩写为:{1}".format(inputStr, acronym(inputStr))) + +def test6_11(): + def squareEach(nums): + for num in range(len(nums)): + nums[num] = nums[num] ** 2 + nums = list(range(10)) + squareEach(nums) + print(nums) + +def test6_12(): + def sumList(nums): + result = 0 + for num in range(len(nums)): + result = result + nums[num] + return result + nums = list(range(10)) + print("列表数字的和为:{0}".format(sumList(nums))) + +def test6_13(): + def toNumbers(strList): + for i in range(len(strList)): + strList[i] = float(strList[i]) + convertList = ["2021", "2020", "2019", "2018"] + print("这是转换之前的列表:{0}".format(convertList)) + toNumbers(convertList) + print("这是转换之后的列表:{0}".format(convertList)) + +def test6_14(): + from tkinter.filedialog import askopenfilename + def sumSquare(nums): + result = 0 + for num in range(len(nums)): + result = result + float(nums[num]) ** 2 + return result + print("请选择需要打开的文件:") + nums = open(askopenfilename(), 'r').readlines() + print("打开文件中数字的平方和为:{0}".format(sumSquare(nums))) + +def test6_15(): + from graphics import GraphWin, Text, Point + def drawFace(center, size, win): + face = Text(center, "笑脸") + face.setSize(size) + face.clone().draw(win) + win = GraphWin("显示笑脸") + drawFace(Point(10, 10), 10, win) + drawFace(Point(100, 100), 36, win) + drawFace(Point(160, 30), 30, win) + win.getMouse() + +def test6_16(): + from graphics import GraphWin, Point, Circle, Line, Image + from tkinter.filedialog import askopenfilename + def drawFace(center, size, win): + Face = Circle(center, size) + Face.setFill('yellow') + Face.clone().draw(win) + Line(Point(center.getX() + size * 0.2, center.getY() + size * 0.3), + Point(center.getX() + size * 0.5, center.getY() + size * 0.3)).draw(win) + Line(Point(center.getX() - size * 0.2, center.getY() + size * 0.3), + Point(center.getX() - size * 0.5, center.getY() + size * 0.3)).draw(win) + def clickDrawFace(win): + center = win.getMouse() + side = win.getMouse() + size = ((center.getX() - side.getX()) ** 2 + (center.getY() - side.getY()) ** 2) ** 0.5 + drawFace(center, size, win) + print("请选择需要遮挡的图片,注意只支持GIF格式!") + 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) + times = int(input("请问需要遮挡的次数:")) + for i in range(times): + clickDrawFace(win) + win.getMouse() + +def test6_17(): + from graphics import GraphWin, Point, Circle + def moveTo(shape, newCenter): + oldCenter = shape.getCenter() + shape.move(newCenter.getX() - oldCenter.getX(), newCenter.getY() - oldCenter.getY()) + win = GraphWin("移动图形", width=800, height=600) + draw = Circle(Point(100, 100), 100) + draw.draw(win) + for i in range(10): + moveTo(draw, win.getMouse()) + win.getMouse() + +import sys +def run(num): + eval("test6_" + num + "()") +run(sys.argv[1]) \ No newline at end of file diff --git a/20210727-第7章.py b/20210727-第7章.py new file mode 100644 index 0000000..e455658 --- /dev/null +++ b/20210727-第7章.py @@ -0,0 +1,143 @@ +# ============================================================================== +# 通过 D:\文档\电子文档\个人\脚本库\PythonScript\第7章.py + 题号 运行 +# 程序名: +# 第7章习题 +# 目的: +# +# 修订记录: +# 日期 编程者 改动描述 +# =================== ============= ===================================== +# 2021-07-27 17:51:57 Sola 7-1 ~ 7-10 略 +# 2021-07-27 19:36:11 Sola 7-11 闰年计算 +# 2021-07-27 19:44:24 Sola 7-12 日期有效性判断 +# 2021-07-27 19:58:14 Sola 7-13 计算某一天是一年中的第几天 +# 2021-07-27 20:11:04 Sola 7-14 ~ 7-15 略,做过了 +# 2021-07-27 20:18:46 Sola 7-16 箭靶计分 +# 2021-07-27 20:39:32 Sola 7-17 弹球 +# 2021-07-27 21:54:58 Sola 7-18 略 + +def IsLeapYear(year): + if year != int(year): + print("错误:请输入整数年份!") + return -1 + if year % 4 == 0 and year % 400 != 0: + return True + else: + return False + +def IsTrueDate(date): + # need function: IsLeapYear + dateList = date.split('/') + day = int(dateList[0]) + month = int(dateList[1]) + year = int(dateList[2]) + if month > 12 or month < 0: + # print("错误:月份范围错误,请检查输入!") + return False + if IsLeapYear(year): + monthList = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + else: + monthList = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + if day > monthList[month - 1] or day < 0: + # print("错误:日期范围错误,请检查输入!") + return False + return True + +def GetDateNum(date): + # need function: IsTrueDate, IsLeapYear + if IsTrueDate(date): + dateList = date.split('/') + day = int(dateList[0]) + month = int(dateList[1]) + year = int(dateList[2]) + if IsLeapYear(year): + monthList = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + else: + monthList = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + dateNum = 0 + for i in range(month - 1): + dateNum = dateNum + monthList[i] + return dateNum + day + else: + return -1 + +def Test7_11(): + year = int(input("请输入年份:")) + if IsLeapYear(year): + print("{0}是闰年".format(year)) + else: + print("{0}不是闰年".format(year)) + +def Test7_12(): + date = input("请按照 dd/mm/yyyy 格式输入日期:") + if IsTrueDate(date): + print("{0} 是有效的日期!".format(date)) + else: + print("{0} 是无效的日期!".format(date)) + +def Test7_13(): + date = input("请按照 dd/mm/yyyy 格式输入日期:") + dateNum = GetDateNum(date) + if dateNum > 0: + print("{0} 是该年份的第{1}天".format(date, dateNum)) + else: + print("错误:输入的日期非法!") + +def Test7_16(): + from graphics import GraphWin, Circle, Text, Point + win = GraphWin() + def draw_circle(r, s_fill): + shape = Circle(Point(100, 90), r) + shape.setFill(s_fill) + shape.setOutline("black") + shape.clone().draw(win) + draw_circle(75, "white") + draw_circle(60, "black") + draw_circle(45, "blue") + draw_circle(30, "red") + draw_circle(15, "yellow") + scoreSum = 0 + scoreText = Text(Point(15, 15), '') + scoreText.draw(win) + for i in range(5): + target = win.getMouse() + score = max(9 - ((target.getX() - 100) ** 2 + (target.getY() - 90) ** 2) ** 0.5 + // 15 * 2, 0) + scoreText.setText(str(int(score))) + scoreSum = scoreSum + score + scoreText.undraw() + Text(Point(100, 180), "Your average score is {0}!\n".format(scoreSum / 5) + + "Click again to quit").draw(win) + win.getMouse() + win.close() + +def Test7_17(): + from graphics import GraphWin, Circle, Text, Point, update + h0 = 144 + x0 = 20 + xx = 0 + win = GraphWin() + win.setCoords(0, 0, 200, 200) + ball = Circle(Point(x0, h0), 20) + ball.setFill("blue") + ball.setOutline("black") + ball.draw(win) + n = 5000 + for i in range(n): + ht = (144 - (i % 24 - 12) ** 2) * (n - i) / n + 20 + vx = 7 * (n - i) / n + xx = xx + vx + xt = 20 + abs(xx % 320 - 160) + dh = ht - h0 + dx = xt - x0 + h0 = ht + x0 = xt + ball.move(dx, dh) + update(30) + Text(Point(100, 100), "Click to quit").draw(win) + win.getMouse() + +import sys +def Run(num): + eval("Test7_" + num + "()") +Run(sys.argv[1]) \ No newline at end of file diff --git a/20210729-第8章.py b/20210729-第8章.py new file mode 100644 index 0000000..74b501b --- /dev/null +++ b/20210729-第8章.py @@ -0,0 +1,311 @@ +# ============================================================================== +# 通过 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 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]) \ No newline at end of file diff --git a/20210801-第9章.py b/20210801-第9章.py new file mode 100644 index 0000000..1e180ce --- /dev/null +++ b/20210801-第9章.py @@ -0,0 +1,293 @@ +# ============================================================================== +# 通过 D:\文档\电子文档\个人\脚本库\PythonScript\第9章.py + 题号 运行 +# 程序名: +# 第9章习题 +# 目的: +# +# 修订记录: +# 日期 编程者 改动描述 +# =================== ============= ===================================== +# 2021-08-01 19:20:17 Sola 9-a 模拟短柄壁球结果 +# 2021-08-01 20:12:22 Sola 9-1 模拟短柄壁球改进 +# 2021-08-01 20:16:29 Sola 9-2 不知道零封是什么规则 +# 2021-08-01 20:16:50 Sola 9-3 没看懂题目说的规则是什么 +# 2021-08-01 20:17:04 Sola 9-4 现代排球比赛 +# 2021-08-01 20:20:56 Sola 9-5 略过 +# 2021-08-01 20:21:04 Sola 9-6 略 +# 2021-08-01 20:21:18 Sola 9-7 花旗骰 +# 2021-08-01 21:07:43 Sola 9-8 21点发牌者爆牌可能性 +# 2021-08-02 00:52:36 Sola 9-9 21点发牌者各首牌爆牌可能性 +# 2021-08-23 20:04:36 Sola 9-10 蒙特卡罗估计PI的值 + +def Test9_a(): + # 击球失误的选手输掉这一回合 + # 如果输家是发球选手,则发球权转给另一名选手 + # 如果发球选手赢得了这一回合,则会得 1 分 + # 选手只能在自己发球时得分 + # 第一名得到 15 分的选手赢得比赛 + from random import random + winProbA = float(input("What is the prob. player A wins a serve? ")) + winProbB = float(input("What is the prob. player B wins a serve? ")) + times = int(input("How many games to simulate? ")) + winsA, winsB = 0, 0 + for i in range(times): + scoreA, scoreB = 0, 0 + servingSide = "A" + while scoreA < 15 and scoreB < 15: + if servingSide == "A": + if random() <= winProbA: + scoreA = scoreA + 1 + else: + servingSide = "B" + else: + if random() <= winProbB: + scoreB = scoreB + 1 + else: + servingSide = "A" + if scoreA > scoreB: + winsA = winsA + 1 + else: + winsB = winsB + 1 + print("\nGames Simulated: {0}".format(times) + + "\nWins for A: {0:3} ({1:4.1%})".format(winsA, winsA / times) + + "\nWins for A: {0:3} ({1:4.1%})".format(winsB, winsB / times)) + +def Test9_1(): + from random import random + winProbA = float(input("What is the prob. player A wins a serve? ")) + winProbB = float(input("What is the prob. player B wins a serve? ")) + times = int(input("How many games to simulate? ")) + winsA, winsB = 0, 0 + for i in range(times): + scoreA, scoreB = 0, 0 + if times % 2 != 0: + servingSide = "A" + else: + servingSide = "B" + while scoreA < 15 and scoreB < 15: + if servingSide == "A": + if random() <= winProbA: + scoreA = scoreA + 1 + else: + servingSide = "B" + else: + if random() <= winProbB: + scoreB = scoreB + 1 + else: + servingSide = "A" + if scoreA > scoreB: + winsA = winsA + 1 + else: + winsB = winsB + 1 + print("\nGames Simulated: {0}".format(times) + + "\nWins for A: {0:3} ({1:4.1%})".format(winsA, winsA / times) + + "\nWins for A: {0:3} ({1:4.1%})".format(winsB, winsB / times)) + +def Test9_4(): + from random import random + winProbA = float(input("What is the prob. player A wins a serve? ")) + winProbB = float(input("What is the prob. player B wins a serve? ")) + times = int(input("How many games to simulate? ")) + winsA, winsB = 0, 0 + for i in range(times): + scoreA, scoreB = 0, 0 + if times % 2 != 0: + servingSide = "A" + else: + servingSide = "B" + while scoreA < 25 and scoreB < 25: + if servingSide == "A": + if random() <= winProbA: + scoreA = scoreA + 1 + else: + servingSide = "B" + scoreB = scoreB + 1 + else: + if random() <= winProbB: + scoreB = scoreB + 1 + else: + servingSide = "A" + scoreA = scoreA + 1 + if scoreA > scoreB: + winsA = winsA + 1 + else: + winsB = winsB + 1 + print("\nGames Simulated: {0}".format(times) + + "\nWins for A: {0:3} ({1:4.1%})".format(winsA, winsA / times) + + "\nWins for A: {0:3} ({1:4.1%})".format(winsB, winsB / times)) + +def Test9_7(): + def main(): + introduce() + times = getValue() + wins = simNGame(times) + printResult(wins, times) + def introduce(): + print("这是一个用来模拟花旗骰的程序:" + + "\n游戏规则如下:" + + "\n1. 一个玩家掷一双普通的六面骰子" + + "\n 1.1 如果初始点数是 2、3 或 12,则玩家失败" + + "\n 1.2 如果是 7 或 11,则玩家获胜" + + "\n 1.3 任何其他初始点数将导致玩家“再掷点”" + + "\n2. 第一轮无结果,则玩家持续掷骰子直到掷出 7 或重新掷出初始点" + + "\n 2.1 如果选手在掷出 7 之前重新掷出初始点,就获胜" + + "\n 2.2 先掷出 7 则失败") + def getValue(): + times = int(input("请输入模拟的次数:")) + return times + def simNGame(times): + wins = 0 + for i in range(times): + wins = wins + result() + return wins + def printResult(wins, times): + print("\n你的模拟获胜次数为:{0:3} ({1:4.1%})".format(wins, wins / times)) + def result(): + firstPoint = getPoint() + if firstPoint == 2 or firstPoint == 3 or firstPoint == 12: + score = 0 + elif firstPoint == 7 or firstPoint == 11: + score = 1 + else: + while True: + thisPoint = getPoint() + if thisPoint == 7: + score = 0 + break + elif thisPoint == firstPoint: + score = 1 + break + return score + def getPoint(): + from random import randrange + return randrange(1, 7) + randrange(1, 7) + main() + +def Test9_8(): + def main(): + introduce() + times = getValue() + booms = simNGame(times) + printResult(booms, times) + def introduce(): + print("二十一点是用纸牌玩的赌场游戏。游戏的目标是拿到尽可能接近 21 点的牌,但不超过。" + + "所有花牌为 10 分,A 为 1 或 11,所有其他牌均按值计分" + + "\n该游戏是针对发牌者进行的。玩家尝试比发牌者更接近 21 点(不超过)" + + "\n1. 如果发牌者爆牌(超过 21),玩家自动获胜(只要玩家尚未爆牌)" + + "\n2. 发牌者必须始终根据固定的规则取牌" + + "\n3. 发牌者至少发牌直到自己达到 17 点以上" + + "\n4. 如果发牌者的牌中包含一个 A,那么如果总和在 17~21 之间时(含 21)" + + ",它将被计为 11" + + "\n5. 否则,A 被计为 1") + def getValue(): + times = int(input("请输入模拟的次数:")) + return times + def simNGame(times): + booms = 0 + for i in range(times): + booms = booms + result() + return booms + def printResult(booms, times): + print("\n模拟发牌者爆牌次数为:{0:3} ({1:4.1%})".format(booms, booms / times)) + def result(): + from random import randrange + sumA, sumB = 0, 0 + hasA, hasB = 0, 0 + while True: + cardA = randrange(1, 12) + if cardA == 1: + hasA = hasA + 1 + sumA = sumA + min(10, cardA) + cardB = randrange(1, 12) + if cardB == 1: + hasB = hasB + 1 + sumB = sumB + min(10, cardB) + if 21 >= sumA + 10 * hasA >= 17 or sumA > 21 or sumB > 21 or (sumA >= 17 and hasA > 0): + break + if sumA > 17 and hasA > 0 and sumB <= 21: + return 1 + elif sumA > 21 and sumB <= 21: + return 1 + else: + return 0 + main() + +def Test9_9(): + def main(): + introduce() + times = getValue() + for j in range(1, 11): + booms = simNGame(times, j) + printResult(booms, times, j) + def introduce(): + print("二十一点是用纸牌玩的赌场游戏。游戏的目标是拿到尽可能接近 21 点的牌,但不超过。" + + "所有花牌为 10 分,A 为 1 或 11,所有其他牌均按值计分" + + "\n该游戏是针对发牌者进行的。玩家尝试比发牌者更接近 21 点(不超过)" + + "\n1. 如果发牌者爆牌(超过 21),玩家自动获胜(只要玩家尚未爆牌)" + + "\n2. 发牌者必须始终根据固定的规则取牌" + + "\n3. 发牌者至少发牌直到自己达到 17 点以上" + + "\n4. 如果发牌者的牌中包含一个 A,那么如果总和在 17~21 之间时(含 21)" + + ",它将被计为 11" + + "\n5. 否则,A 被计为 1") + def getValue(): + times = int(input("请输入每个首牌模拟的次数:")) + return times + def simNGame(times, j): + booms = 0 + for i in range(times): + booms = booms + result(j) + return booms + def printResult(booms, times, card): + print("首牌为{2:2}时,模拟发牌者爆牌次数为:{0:5} ({1:4.1%})".format(booms, booms / times, card)) + def result(j): + from random import randrange + sumA, sumB = 0, 0 + hasA, hasB = 0, 0 + cardA = j + if cardA == 1: + hasA = hasA + 1 + sumA = sumA + min(10, cardA) + cardB = randrange(1, 12) + if cardB == 1: + hasB = hasB + 1 + sumB = sumB + min(10, cardB) + while True: + cardA = randrange(1, 12) + if cardA == 1: + hasA = hasA + 1 + sumA = sumA + min(10, cardA) + cardB = randrange(1, 12) + if cardB == 1: + hasB = hasB + 1 + sumB = sumB + min(10, cardB) + if 21 >= sumA + 10 * hasA >= 17 or sumA > 21 or sumB > 21 or (sumA >= 17 and hasA > 0): + break + if sumA > 17 and hasA > 0 and sumB <= 21: + return 1 + elif sumA > 21 and sumB <= 21: + return 1 + else: + return 0 + main() + +def Test9_10(): + def main(): + introduce() + times = getInput() + PIvalue = coculate(times) + printResult(PIvalue) + def introduce(): + print("该程序接受飞镖数作为输入,然后进行模拟估计PI") + def getInput(): + times = int(input("请输入飞镖数:")) + return times + def coculate(times): + sum = 0 + for i in range(times): + + + +import sys +def Run(num): + eval("Test9_" + num + "()") +Run(sys.argv[1]) \ No newline at end of file