当前位置: 首页 > news >正文

Python练习3

1. 编写程序完成以下功能

猴子第一天摘下若干桃子,当即吃了一半,还不过瘾,又多吃了一个;
第二天又将剩下的桃子吃掉一半,不过瘾又多吃了一个;
以后每天都吃了前一天剩下的一半多一个。
到第五天想再吃时,见到只剩下一个桃子了。
编程计算猴⼦第⼀天⼀共摘了多少个桃⼦? 

# day5:1;
# day4:(1+1)* 2=4
# day3:(4+1)*2=10
# day2:(10+1)*2=22
# day1:(22+1)*2=46# 方法一:第5天到第1天反向计算(for循环)
t = 1 # 第5天的1个桃子
for i in range(1,5):t = (t+1)*2
print(t)
# 方法二:第5天到第1天反向计算(while循环)
day=4
num=1
while day>=1:num=2*(num+1)day-=1
print(num)
# 方法三:函数调用
n = 1
def eat(n):return (n+1)*2
# i用来记录天数,每一天都调用一次
for i in range(1, 5):n = eat(n)
print(f'第⼀天⼀共摘了{n}个桃⼦')
# 方法四:位运算
n = 1
# i用来记录天数,每一天都调用一次
# 和方法三不同的是,这里是5到1反向遍历
for i in range(5,1,-1):n=(n+1)<<1 # 位运算符中,左移一位代表这个值*2
print (n)
# 方法五:list记录桃子个数
# list用于存储每一天桃子的个数,已知第5天个数为1
list = [0,0,0,0,1]
# 遍历list
for i in range(1,5):list[4-i] = (list[4-i+1] + 1) * 2
print(f"猴⼦第⼀天⼀共摘了{list[0]}个桃⼦")

2. 根据列表中保存的数据采⽤turtle库画出直方图,显示在屏幕上,效果如下图所示。

注意:方法一运行结果与上图一致,其他方法只是用来向大家介绍一下其他绘制直方图的方法。

# 方法一
import turtle  # 导入turtle库t = turtle  # 用t来代替turtle,比较方便# 定义一个画直方图的函数
def line(n, color, x, y):t.pensize(n)  # 设置画笔大小t.pencolor(color)t.penup()t.goto(-150 + x, -50)  # 画笔去到落笔点t.pendown()t.goto(-150 + x, -50 + y)  # 画出直方图# 主程序
ls = [69, 292, 33, 131, 61, 254]  # 题目数据# x轴
n = 1  # 设置画笔粗细
color = "#000000"  # 设置画笔颜色为黑色
a = 400
b = 0
t.penup()
t.goto(-150, -50)
t.pendown()
t.goto(-150 + a, -50)# y轴
a = 0
b = 300
line(n, color, a, b)  # 画出y轴# 利用循环画出直方图
n = 5  # 设置画笔粗细
color = "#FF0000"  # 设置画笔颜色为正红色
for i in range(0, len(ls)):a = (i + 1) * 50b = ls[i]line(n, color, a, b)t.done()  # 防止窗口闪退
# 方法二
import turtle  # 导入turtle模块,用于绘图# 设置绘图窗口的大小为800x600,不显示滚动条
turtle.setup(800, 600, 0, 0)# 移动到窗口的左下角,准备开始绘制
turtle.forward(-300)  # 向前移动300个单位
turtle.left(90)       # 左转90度# 绘制直方图的底部
turtle.forward(200)  # 向前移动200个单位
turtle.forward(-200) # 返回原点
turtle.right(90)     # 右转90度,准备绘制直方图的左侧边# 绘制直方图的左侧边
turtle.forward(30)  # 向前移动30个单位# 开始绘制直方图的每个条形
for i in [69, 292, 33, 131, 61, 254]:  # 遍历数据列表turtle.fillcolor('red')  # 设置填充颜色为红色turtle.begin_fill()     # 开始填充颜色# 绘制每个条形turtle.left(90)         # 左转90度,准备向上绘制turtle.forward(i)       # 向前移动i个单位,绘制条形的高度turtle.right(90)        # 右转90度,准备向右绘制turtle.forward(10)      # 向右移动10个单位,绘制条形的宽度turtle.right(90)        # 右转90度,准备向下绘制turtle.forward(i)       # 向下移动i个单位,完成条形的绘制turtle.end_fill()       # 结束填充颜色# 移动到下一个条形的起始位置turtle.left(90)         # 左转90度turtle.forward(30)      # 向前移动30个单位# 完成绘图
turtle.done()
# 这里给大家展示一下怎样画出坐标轴的箭头
import turtle  # 导入turtle模块,用于绘图# 定义一个函数来计算坐标转换
def D(x, y):return x - 300, y  # 返回调整后的坐标# 定义一个函数来画坐标轴
def x_y(pen, x_name='x', y_name='y'):pen.pensize(2)  # 设置画笔粗细为2pen.up()  # 抬起画笔,移动时不绘图pen.goto(D(0, 0))  # 移动到原点pen.down()  # 放下画笔,开始绘图# 绘制x轴pen.goto(D(600, 0))  # 向右移动600个单位pen.goto(D(595, 5))  # 向上移动5个单位pen.goto(D(600, 0))  # 返回原点pen.goto(D(595, -5))  # 向下移动5个单位# 标记x轴pen.up()  # 抬起画笔pen.goto(D(600, -20))  # 移动到x轴标签位置pen.goto(D(0, 0))  # 返回原点pen.down()  # 放下画笔# 绘制y轴pen.goto(D(0, 300))  # 向上移动300个单位pen.goto(D(-5, 295))  # 向左移动5个单位pen.goto(D(0, 300))  # 返回原点pen.goto(D(5, 295))  # 向右移动5个单位# 标记y轴pen.up()  # 抬起画笔pen.goto(D(-28, 305))  # 移动到y轴标签位置pen.down()  # 放下画笔# 创建一个turtle对象
t = turtle.Pen()
t.hideturtle()  # 隐藏turtle图标# 调用函数绘制坐标轴
x_y(t)# 移动到指定位置
turtle.goto(-200, 0)  # 移动到(-200, 0)的位置turtle.done()  # 完成绘图
# 方法三
import turtle  # 导入turtle模块# 设置画布大小为1.0x1.0,这里应该是屏幕的某个比例,而不是1:1
turtle.setup(1.0, 1.0)# 设置画笔速度为3,速度范围是1(最慢)到10(最快)
turtle.speed(3)# 绘制一个半径为10,颜色为红色的点作为原点
turtle.dot(10, 'red')# 在原点旁边标注'o',字体为Times New Roman,大小为20
turtle.write('o', align='left', font=('Times New Roman', 20))# 设置画笔的粗细为3
turtle.pensize(3)# 移动到坐标(350, 0)的位置,并标注'x'
turtle.goto(350, 0)
turtle.write('x', align='left', font=('Times New Roman', 20))# 回到原点(0, 0)
turtle.home()# 移动到坐标(0, 350)的位置,并标注'y'
turtle.goto(0, 350)
turtle.write('y', align="left", font=('Times New Roman', 20))# 回到原点(0, 0)
turtle.home()# 循环绘制柱状图,柱状图的高度由列表中的数值决定
for i in [69, 292, 33, 131, 61, 254]:# 设置填充颜色为红色turtle.fillcolor('red')# 开始填充turtle.begin_fill()# 转向90度,使画笔垂直于x轴turtle.left(90)# 向前移动到柱状图的顶部turtle.forward(i)# 向右转90度,使画笔平行于x轴turtle.right(90)# 向前移动40个单位,这是柱状图的宽度turtle.forward(40)# 向右转90度,使画笔垂直于x轴turtle.right(90)# 向前移动到柱状图的底部turtle.forward(i)# 结束填充turtle.end_fill()# 向左转90度,使画笔回到初始方向turtle.left(90)# 结束绘图
turtle.done()
# 方法四
import turtle  # 导入turtle模块heights = [69, 292, 33, 131, 61, 254]  # 柱状图的高度列表def main():  # 主函数定义t = turtle.Turtle()  # 创建一个Turtle对象t.hideturtle()  # 隐藏turtle形状for i in range(6):  # 循环6次,绘制6个柱状图drawFilledRectangle(t, -200 + (76 * i), 0, 6, heights[i] / 4, "black", "light blue")  # 绘制填充矩形# 第三个逗号后的参数是控制柱子的粗细displayText(t)  # 显示文本def drawFilledRectangle(t, x, y, w, h, colorP="black", colorF="white"):  # 绘制填充矩形的函数t.pencolor(colorP)  # 设置画笔颜色t.fillcolor(colorF)  # 设置填充颜色t.up()  # 抬起画笔t.goto(x, y)  # 移动到矩形的起始位置t.down()  # 放下画笔t.begin_fill()  # 开始填充t.goto(x + w, y)  # 绘制矩形的边t.goto(x + w, y + h)t.goto(x, y + h)t.end_fill()  # 结束填充def displayText(t):  # 显示文本的函数languages = ["", "", "", "", "", ""]  # 语言列表t.pencolor("blue")  # 设置画笔颜色为蓝色t.up()  # 抬起画笔for i in range(6):  # 循环6次,显示每个柱状图上方的文本t.goto((-192 + 73 * i), heights[i] / 4)  # 移动到柱状图上方的位置t.write(str(heights[i]))  # 显示柱状图的高度t.goto((-192 + 73 * i), 10)  # 移动到柱状图底部的位置t.write(languages[i])  # 显示语言名称t.goto(-200, -25)  # 移动到图表标题的位置t.write("Language Popularity")  # 显示图表标题t.goto(-200, -45)  # 移动到图表副标题的位置t.write("(in thousands)")  # 显示图表副标题main()  # 调用主函数
turtle.done()  # 结束绘图
# 方法五:用matplotlib库
import turtle  # 导入turtle模块,虽然在这段代码中并没有使用到
import matplotlib.pyplot as plt  # 导入matplotlib的pyplot模块,用于绘制图表# 设置matplotlib的参数,使得可以正常显示中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体字体
plt.rcParams['axes.unicode_minus'] = False  # 解决负号'-'显示为方块的问题# 定义类别和对应的数值
categories = ('A', 'B', "C", 'D', 'E','F')  # 类别列表,注意这里的字符串应该使用英文的逗号和引号
number = [69, 292, 33, 131, 61, 254]  # 每个类别对应的数值列表# 使用plt.bar函数绘制直方图,categories作为x轴的标签,number作为每个条形的高度
plt.bar(categories, number)# 设置图表的标题
plt.title('直方图')# 显示图表
plt.show()

3、用户输入8位日期,判断该日期是这一年的第几天。

要求不要调用外部函数,编写具备完整功能的程序。(格式如:20201028)

(1)使用字典存放闰年和非闰年的每月天数;
(2)当用户输入错误的日期格式(非数字或错误的月份或日期)时,给出提示信息并等待重输;

# 方法一
def day(x):# 定义每个月的天数month = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}month4 = {1: 31, 2: 29, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}y = int(x[0:4])  # 取前四位年份a = int(x[4:6])  # 取月份b = int(x[6:])   # 取日期s = 0  # 初始化天数总和# 判断月份是否合法if a < 1 or a > 12:print("输入的月份不合法,请重新输入!")return# 判断日期是否合法if b < 1:print("输入的日期不合法,请重新输入!")returnif b > month[a] and (not (a == 2 and b == 29 and ((y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)))):print("输入的日期不合法,请重新输入!")return# 判断是否为闰年if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0):for i in range(1, a):s += month4[i]else:for i in range(1, a):s += month[i]s += bprint(f"该日期为这一年的第{s}天")while True:n = input("请输入8位日期(格式为20241020),输入'q'退出:\n")if n.lower() == 'q':breakif len(n) != 8 or not n.isdigit():print("输入格式不正确,请输入8位数字日期。")else:day(n)
# 方法二
# 用字典分别表示闰年和非闰年的月份及对应天数
runnian = {"一月": 31, "二月": 29, "三月": 31, "四月": 30, "五月": 31, "六月": 30, "七月": 31, "八月": 31, "九月": 30, "十月": 31, "十一月": 30, "十二月": 31}
pinnian = {"一月": 31, "二月": 28, "三月": 31, "四月": 30, "五月": 31, "六月": 30, "七月": 31, "八月": 31, "九月": 30, "十月": 31, "十一月": 30, "十二月": 31}# 将数字月份与文字月份对应起来
M = ("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月")def is_valid_date(year, month, date):# 检查月份是否合法if month < 1 or month > 12:return False# 检查日期是否合法if date < 1:return False# 检查2月份的日期是否合法,考虑闰年情况if month == 2:if ((year % 4 == 0 and year % 100 != 0)) or (year % 400 == 0):return date <= 29else:return date <= 28# 检查其他月份的日期是否合法return date <= runnian[M[month - 1]]while True:data = input("请输入8位日期,格式如:20240102:\n")# 如果输入不是8位让用户重输if len(data) != 8 or not data.isdigit():print("请输入正确的格式")else:year = int(data[0:4])month = int(data[4:6])date = int(data[6:])# 判断日期是否合法if is_valid_date(year, month, date):# 计算这是一年中的第几天sum = 0if ((year % 4 == 0 and year % 100 != 0)) or (year % 400 == 0):  # 闰年for i in range(1, month):sum += runnian[M[i - 1]]else:  # 非闰年for i in range(1, month):sum += pinnian[M[i - 1]]sum += dateprint(f"该日期是这一年的第{sum}天")else:print("请输入正确的日期格式")
# 方法三
def is_leap_year(year):  # 判断是否为闰年return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)# 平年时每月的天数
month_dict_0 = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}# 闰年时每月的天数
month_dict_1 = {1: 31, 2: 29, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}def get_y_m_d(date):  # 根据输入的日期获取年月日,若输入日期非法,则年月日均返回-1year = int(date[0:4])month = int(date[4:6])day = int(date[6:8])if year < 1 or month < 1 or month > 12 or day < 1 or day > (month_dict_0[month] if not is_leap_year(year) or month != 2 else month_dict_1[month]):return -1, -1, -1return year, month, daywhile True:date = input("请输入一个8位日期(格式如:20240102):\n")if len(date) != 8 or not date.isdigit():  # 不是8位或不是整数print("输入日期非法,请重新输入!")else:year, month, day = get_y_m_d(date)if year == -1:print("输入日期非法,请重新输入!")else:break  # 输入合法,跳出循环res = 0  # 存放天数
if is_leap_year(year):  # 闰年for mon in range(1, month):  # 循环相加本月前的天数res += month_dict_1[mon]  # 加上本月中的天数
else:  # 平年for mon in range(1, month):res += month_dict_0[mon]res += day
print(f"{year}年{month}月{day}日是{year}年的第{res}天")

4、完成拼写单词的小游戏程序

        程序内置某序列类型以存放30个不同的单词(要求每个单词字符数不低于6个)。每次运行游戏时,从30个单词中随机取出10个放入单词池待用。执行后随机选择其中一个单词,将其打乱顺序显示,待用户拼写出正确的单词后继续显示下一个。不能重复使⽤,当⼗个单词⽤完,则给出提示(显示得分(每题⼗分)和拼写错误的单词(原词和错误答案))并终⽌程序。

import random# 导入random随机模块
words = ('python', 'computer', 'absorb', "wonderful", 'excellent', 'mammal', 'sister','source', 'vision', 'melody', 'effort', 'intend', 'defeat', "galaxy",'successful', 'holder', 'escape', 'conductor', 'bridge', 'character','beautiful', 'kilometer', 'important', 'nature', 'output', 'person','impact'
)print('每题您仅有一次机会得分,答对得10分,答错您将不断尝试直到答对才能进行下一题,共10题,加油!')
test = random.sample(words, 10)  # sample从指定序列中随机获取指定长度元素
score = 0  # 分数初始值
correct = []  # 存储正确的答案
wrong = []  # 存储错误的单词for i in range(10):  # 循环抽取10次select_word = random.choice(test)  # 在test序列中随机抽取单词test.remove(select_word)  # 删除test序列中已抽出的单词,即无放回的随机抽取reword = ''.join(random.sample(select_word, len(select_word)))  # 随机获取单词的字母,注意长度为单词总字母数量,可视作乱序print(reword)  # 出题input_word = input('请正确拼写单词:')while input_word != select_word:  # 拼写错误需要不断循环继续拼写wrong.append(input_word)  # 添加错误的输入print("拼写错误,请重新拼写:")input_word = input('请重新拼写:')score += 10  # 拼写的单词正确则加10分correct.append(select_word)  # 添加正确的答案print('总分100分,您的得分为' + str(score) + '分')
if wrong:print('您出错的单词及正确拼写为:')for i in range(len(wrong)):print('您的错误拼写为:' + wrong[i] + ',正确拼写为:' + correct[i])
else:print('恭喜您,所有单词都拼写正确!')
# 方法二
import random
import string# 内置的单词列表,确保每个单词长度不低于6个字符
words = ["algorithm", "function", "variable", "python", "programming", "dictionary","define", "mortality", "bookstore", "recursion", "class", "inheritance", "benefit","instance", "method", "library", "homework", "dialogue", "parameter", "thoughtful","decoding", "encoding", "compiler", "portray", "syntax", "semantic", "debugging","exception", "imminent", "performance"
]# 打乱单词顺序
def scramble_word(word):word_list = list(word)random.shuffle(word_list)return ''.join(word_list)def main():selected = random.sample(words, 10)score = 0wrong_answers = {}for word in selected:mess_word = scramble_word(word)print("请输入正确的单词(已打乱): ", mess_word)my_answer = input("我的答案是: ").strip()if my_answer == word:print("正确")score += 10else:print(f"错误, 正确答案是: {word}")wrong_answers[word] = my_answerprint(f"游戏结束,得分: {score}/100")if wrong_answers:print("拼错的单词:")for correct, wrong in wrong_answers.items():print(f"原词: {correct},你的答案: {wrong}")if __name__ == "__main__":main()
# 方法三
import tkinter as tk
import random# 按钮“提交”绑定事件
def event_but_submit(event):global level, score, submit, lastword = entry_word.get()if word == words_ten[level - 1]:result = "猜对了!"score += 10else:result = "猜错了!"words_mistake.append(word)words_right.append(words_ten[level - 1])textvar.set(result)submit = 1  # 提交标志位为1,表示已经提交# 按钮“偷看答案”绑定事件
def event_but_answer(event):textentry.set(words_ten[level - 1])  # 文本框内容设置为原词# 按钮“下一题”绑定事件
def event_but_next(event):global word, level, rank, last, submitif submit == 0:  # 如果还没提交,则自动提交event_but_submit(event)submit = 0if last == 1:  # 如果已经是最后一题,显示最终结果finalresult()else:level += 1textlevel.set("第" + str(level) + " 题" + "(共10题)")rank += 1word = words_ten[rank]word_shuffle = "".join(random.sample(word, len(word)))textguess.set("您要猜的单词包含字母为: " + word_shuffle)entry_word.delete(0, "end")textvar.set("")if level == 10:  # 到第10题时textnext.set("已是最后一题,点此按钮查看结果")  # 按钮内容更改last = 1# 按钮“关闭”绑定事件
def event_but_close(event):root.destroy()# 显示最终结果
def finalresult():root1 = tk.Tk(className="最终结果")root1.geometry("400x300+600+200")label_word = tk.Label(root1, width=80, text="得分: " + str(score))label_word.pack(side="top", anchor='nw', padx=10)for i in range(len(words_right)):label_word = tk.Label(root1, width=80, text='原词: ' + words_right[i] + '\n错误的单词: ' + words_mistake[i])label_word.pack(side="top", anchor="nw", padx=10)# 主窗口
root = tk.Tk(className="猜单词")
root.geometry("400x200+600+200")# 存储错误单词
words_mistake = []
words_right = []  # 存储原词
last = 0  # 是否全部题目都做完标志位
rank = 0  # 抽取到的第x个单词
level = 1  # 表示第x题
score = 0  # 分数
submit = 0  # 每道题是否提交标志位# 单词列表
words = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October", "November", "December", "millimetre","centimetre", "displeasure", "thirsty", "micron", "nanometre", "anxious", "sorrowful", "emotion", "terrible"
]# 随机选择10个单词
words_ten = random.sample(words, 10)
word = words_ten[rank]  # 当前词
word_shuffle = "".join(random.sample(word, len(word)))# 创建第x题显示标签
textlevel = tk.StringVar()
textlevel.set("第" + str(level) + " 题" + "(共10题)")
label_level = tk.Label(root, width=80, textvariable=textlevel)
label_level.pack(side="top", padx=10)# 创建题目描述显示标签
textguess = tk.StringVar()
textguess.set("您要猜的单词包含字母为: " + word_shuffle)
label_word = tk.Label(root, width=80, textvariable=textguess)
label_word.pack(side="top", padx=10)# 创建输入框
textentry = tk.StringVar()
entry_word = tk.Entry(root, width=40, textvariable=textentry)
entry_word.pack(side="top", padx=10)
entry_word.bind('<Return>', event_but_submit)# 创建按钮子框
fm1 = tk.Frame(root)
fm1.pack(side='top', fill='both', expand='yes')# 创建“提交”按钮
but_submit = tk.Button(fm1, text="提交")
but_submit.pack(side="left", padx=10)
but_submit.bind('<Button-1>', event_but_submit)# 创建“偷看答案”按钮
but_answer = tk.Button(fm1, text="偷看答案")
but_answer.pack(side="left", padx=10)
but_answer.bind('<Button-1>', event_but_answer)# 创建“下一题”按钮
textnext = tk.StringVar()
textnext.set("下一题")
but_next = tk.Button(fm1, textvariable=textnext)
but_next.pack(side="left", padx=10)
but_next.bind('<Button-1>', event_but_next)# 创建“关闭”按钮
but_close = tk.Button(fm1, text="关闭")
but_close.pack(side="right", padx=10)
but_close.bind('<Button-1>', event_but_close)# 创建每道题结果显示
textvar = tk.StringVar()
label_oneresult = tk.Label(root, width=80, textvariable=textvar, anchor='w')
label_oneresult.pack(side='top', padx=10)# 单行文本框获得焦点
entry_word.focus_set()# 主体的死循环
root.mainloop()


http://www.mrgr.cn/news/54869.html

相关文章:

  • 面试后的想法
  • C++源码生成·序章
  • 机器学习核心:监督学习与无监督学习
  • C/C++ 每日一练:单链表的反转
  • 枚举的使用举例说明
  • MongoDB的基本操作
  • 空间复杂度
  • Java程序OutOfMemoryError分析与heap dump
  • Chromium127编译指南 Windows篇 - depot_tools工具的安装与设置(二)
  • 三种容器 std::vector、std::map、std::unordered_set 的对比分析
  • 【热门主题】000004 案例 Vue.js组件开发
  • C++算法练习-day11——242.有效的字母异位词
  • CSS网页布局(重塑网页布局)
  • (A-D)AtCoder Beginner Contest 376
  • es的DSL查询语句
  • 权限(补充)
  • 求一个无符号整数二进制形式中1的个数(三种方法)
  • DDD通用语言、多尿和尿频-《分析模式》漫谈41
  • 1. 解读DLT698.45-2017通信规约--预连接响应
  • upload-labs靶场Pass-05
  • 第五届人工智能与教育国际学术会议(ICAIE 2024)
  • (五)若使用LQR控制小车倒立摆,该如何对小车和摆杆的动力学方程线性化?哪些变量是可以进行简化的,线性化后的状态空间方程应该怎么列写
  • 瑞数后缀加密怎么处理
  • 大厂面试提问:Flash Attention 是怎么做到又快又省显存的?
  • 多线程编程
  • 多表使用use_hash hint