栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

4.Python 巩固练习

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

4.Python 巩固练习

文章目录
  • Python 练习题
    • 练习题1 : 两数之和
    • 练习题2 : 数字阶乘
    • 练习题3 : 求圆面积
    • 练习题4 : 求区间内所有素数
    • 练习题5 : 求前n个数字的平方和
    • 练习题6 : 计算列表数字的和
    • 练习题7 : 计算数字范围中所有偶数
    • 练习题8 : 移除列表中多个元素
    • 练习题9 : 列表元素去重
    • 练习题10 : 简单列表排序
    • 练习题11 : 学生成绩排序
    • 练习题12 : 读取成绩文件排列数据
    • 练习题13 : 统计学生成绩高低分平均分
    • 练习题14: Python统计英语文章中出现最多的单词数目
    • 练习题15 : 统计目录下所有文件大小
    • 练习题16 : 按文件后缀整理文件夹
    • 练习题17 : Python递归搜索目录找出最大的文件
    • 练习题18 : 计算班级的高分低分平均分
    • 练习题19 : Python实现不同文件的关联
    • 练习题20 : Python实现批量txt文件的合并
    • 练习题21 : Python统计每个兴趣的学生人数
    • 练习题22 : Python获取当前的日期和时间
    • 练习题23 : Python计算两个日期相隔的天数

Python 练习题 练习题1 : 两数之和
"""
    need:
        输入两个数字,打印数字之和
"""

numbers1 = 1.5
numbers2 = 3.8

sum = numbers1 + numbers2

print(f"{numbers1} + {numbers2} = {sum}")

练习题2 : 数字阶乘
def get_jiecheng(number):
    result = 1
    while number > 0:
        result *= number    # result = result * number
        number -= 1         # number = number - 1
    return result


print(f"阶乘 3 = {get_jiecheng(3)}")
print(f"阶乘 6 = {get_jiecheng(6)}")
print(f"阶乘 10 = {get_jiecheng(10)}")
练习题3 : 求圆面积
"""
    need:
        输入半径返回圆的面积.
    help:
        圆的面积公式:S=πr^2
"""
import math


def compute_area_of_circle(r):
    return round(math.pi * r * r, 2)


print(f"area of 2 is:{compute_area_of_circle(2)}")
print(f"area of 4.6 is:{compute_area_of_circle(4.6)}")
print(f"area of 7 is:{compute_area_of_circle(7.12)}")

练习题4 : 求区间内所有素数
"""
    need:
        输入开始数字和结束数字,打印区间内所有的素数(如输入11和25,打印11~25间的所有素数,包括25)
    help:
        素数:指数字只能被1和自己整除的数,如3、4等.
"""


def is_prime(number):
    if number in (1, 2):
        return True
    for idx in range(2, number):
        if number % idx == 0:
            return False
    return True


def print_primes(begin, end):
    for number in range(begin, end + 1):
        if is_prime(number):
            print(f"{number} is a prime")


begin = 11
end = 25
print_primes(begin, end)
练习题5 : 求前n个数字的平方和
"""
    need:
        输入: 数字n
        计算: 1**2 + 2**2 + 3**3 + ... + n**n
"""


def sum_of_square(n):
    result = 0
    for number in range(1, n + 1):
        result += number * number
    return result


print(f"sum of square 3: {sum_of_square(3)}")
print(f"sum of square 3: {sum_of_square(5)}")
print(f"sum of square 3: {sum_of_square(7)}")
练习题6 : 计算列表数字的和
"""
    need:
        输入: [1,2,3,4], 输出: 10
        输入: [17,5,3,5], 输出: 30
"""


def sum_of_list(param_list):
    total = 0
    for item in param_list:
        total += item
    return total


list1 = [1, 2, 3, 4]
list2 = [17, 5, 3, 5]

print(f"sum of {list1},", sum_of_list(list1))
print(f"sum of {list1},", sum_of_list(list2))

print("-----------------")

print(f"sum of {list1},", sum(list1))
print(f"sum of {list1},", sum(list2))
练习题7 : 计算数字范围中所有偶数
"""
    need:
        输入开始和结束值(不包含),得到所有偶数
        如:
            输入: begin=4,end=15
            返回: [4,6,8,10,12,14]
    help:
        偶数:能够被2所整除的整数,是2的倍数
"""


def get_even_numbers(begin, end):
    result = []
    for item in range(begin, end):
        if item % 2 == 0:
            result.append(item)
    return result


begin = 4
end = 15
print(f"begin={begin},end={end},even number:", get_even_numbers(begin, end))


print("-----------------------")


data = [item for item in range(begin, end) if item % 2 == 0]
print(f"begin={begin},end={end},even number:", data)
练习题8 : 移除列表中多个元素
"""
    need:
        输入:
            - 原始列表: [3,5,7,9,11,13]
            - 移除元素: [7,11]
        返回:
            - [3,5,9,13]
"""


def remove_elements_from_list(lista, listb):
    for item in listb:
        lista.remove(item)
    return lista


lista = [3, 5, 7, 9, 11, 13]
listb = [7, 11]

print(f"from {lista} remove {listb}, result: ", remove_elements_from_list(lista, listb))


print("-----------------------")


lista = [3, 5, 7, 9, 11, 13]
listb = [7, 11]
data = [item for item in lista if item not in listb]
print(f"from {lista} remove {listb}, result: ", data)
练习题9 : 列表元素去重
"""
    need:
        输入包含重复元素的原始列表: [10, 20, 30, 10, 20]
        返回: [10, 20, 30]
"""


def get_unique_list(lista):
    result = []
    for item in lista:
        if item not in result:
            result.append(item)
    return result


lista = [10, 20, 30, 10, 20]
print(f"source list {lista}, unique list:", get_unique_list(lista))


print("-----------------------")


print(f"source list {lista}, unique list:", list(set(lista)))
练习题10 : 简单列表排序
"""
    need:
        怎样对简单列表排序?
            - 简单列表: 元素类型不是复合类型(列表/元组/字典)
            - 形式1: [20, 50, 10, 40, 30]
            - 形式2: ['bb', 'ee', 'aa', 'dd', 'cc']
    help:
        知识点:
            - 怎样原地排序?怎样不改变原列表排序
            - 怎样指定是升序排序还是降序排序
"""
lista = [20, 50, 10, 40, 30]
lista.sort(reverse=True)  # 降序排列
print(f"lista is {lista}")

listb = [20, 50, 10, 40, 30]
listb.sort(reverse=False)  # 升序排列
print(f"listb is {listb}")
练习题11 : 学生成绩排序
"""
    need:
        学生成绩数据格式:
            -复杂列表, 元素是字典或者元组
            - [
                {'sno': 101, 'sname': "小张", 'sgrade': 88},
                {'sno': 102, 'sname': "小王", 'sgrade': 77},
                {'sno': 103, 'sname': "小李", 'sgrade': 99},
                {'sno': 104, 'sname': "小赵", 'sgrade': 66},
                ]

"""

students = [
    {'sno': 101, 'sname': "小张", 'sgrade': 88},
    {'sno': 102, 'sname': "小王", 'sgrade': 77},
    {'sno': 103, 'sname': "小李", 'sgrade': 99},
    {'sno': 104, 'sname': "小赵", 'sgrade': 66},
]

student_sort = sorted(
    students,                       # 数据源
    key=lambda x: x["sgrade"],      # 排序依据
    reverse=True                    # 降序
)

print(students)
print(student_sort)
练习题12 : 读取成绩文件排列数据
# 12_Data.txt

103,小李,99
101,小张,88
102,小王,77
104,小赵,66
105,小强,55
"""
    need:
        1.输入文件:
            三列: 学号、姓名、成绩
            列之间用逗号分隔,如 "101,小张,88"
            行之间用n换行分割
        2.处理:
            读取文件,按成绩倒序排列
        3.输出:
            排序后的三列数据
"""


def read_file():
    result = []
    with open("./fileSave/12_Data.txt", encoding="utf-8") as fin:
        for line in fin:
            line = line[:-1]
            # print(line)
            result.append(line.split(","))
            # print(result)
    return result


def sort_grades(datas):
    return sorted(
        datas,
        key=lambda x: int(x[2]),
        reverse=True
    )


def write_file(datas):
    with open("./fileSave/12_DataOut.txt", "w", encoding="utf-8") as fout:
        for data in datas:
            fout.write(",".join(data) + "n")


# 读取文件
datas = read_file()
print("read_file datas:", datas)

# 排序数据
datas = sort_grades(datas)
print("sort_grades datas:", datas)

# 写出文件
write_file(datas)

练习题13 : 统计学生成绩高低分平均分
# 13_Data.txt

103,小李,99
101,小张,88
102,小王,77
104,小赵,66
105,小强,55
"""
    need:
        输入文件:
            1.三列: 学号、姓名、成绩
            2.列之间用逗号分割,如"101,小张,88"
            3.行之间用n换行分割
        输出: 最高分、最低分、平均分
"""


def compute_score():
    scores = []
    with open("fileSave/13_Data.txt") as fin:
        for line in fin:
            line = line[:-1]
            fields = line.split(",")
            scores.append(int(fields[-1]))
    max_score = max(scores)
    min_score = min(scores)
    avg_score = round(sum(scores) / len(scores), 2)
    return max_score, min_score, avg_score


max_score, min_score, avg_score = compute_score()
print(f"max_score={max_score}, min_score={min_score}, avg_score={avg_score}")
练习题14: Python统计英语文章中出现最多的单词数目
# 14_Data.txt

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
word_count = {}

with open("./fileSave/14_Data.txt") as fin:
    for line in fin:
        line = line[:-1]  # 去掉末尾换行符
        words = line.split()  # 以空格分割,一个单词为一个元素(字符串)
        for word in words:
            if word not in word_count:
                word_count[word] = 0
            word_count[word] += 1

times = sorted(
    word_count.items(),  # 取键值对
    key=lambda x: x[1],  # 比较出现的次数
    reverse=True  # 降序排列
)[:10]  # 取出现频率最高的前十个词

for i in times:
    print(i)

练习题15 : 统计目录下所有文件大小
# 15_Data.txt

秋天的怀念
双腿瘫痪后,我的脾气变得暴怒无常。望着望着天上北归的雁阵,我会突然把面前的玻璃砸碎;听着听着李谷一甜美的歌声,我会猛地把手边的东西摔向四周的墙壁。母亲就悄悄地躲出去,在我看不见的地方偷偷地听着我的动静。当一切恢复沉寂,她又悄悄地进来,眼边红红的,看着我。“听说北海的花儿都开了,我推着你去走走。”她总是这么说。母亲喜欢花,可自从我的腿瘫痪以后,她侍弄的那些花都死了。“不,我不去!”我狠命地捶打这两条可恨的腿,喊着,“我可活什么劲儿!”母亲扑过来抓住我的手,忍住哭声说:“咱娘儿俩在一块儿,好好儿活,好好儿活……”
可我却一直都不知道,她的病已经到了那步田地。后来妹妹告诉我,她常常肝疼得整宿整宿翻来覆去地睡不了觉。

那天我又独自坐在屋里,看着窗外的树叶“唰唰啦啦”地飘落。母亲进来了,挡在窗前:“北海的菊花开了,我推着你去看看吧。”她憔悴的脸上现出央求般的神色。“什么时候?”“你要是愿意,就明天?”她说。我的回答已经让她喜出望外了。“好吧,就明天。”我说。她高兴得一会坐下,一会站起:“那就赶紧准备准备。”“哎呀,烦不烦?几步路,有什么好准备的!”她也笑了,坐在我身边,絮絮叨叨地说着:“看完菊花,咱们就去‘仿膳’,你小时候最爱吃那儿的豌豆黄儿。还记得那回我带你去北海吗?你偏说那杨树花是毛毛虫,跑着,一脚踩扁一个……”她忽然不说了。对于“跑”和“踩”一类的字眼,她比我还敏感。她又悄悄地出去了。
她出去了,就再也没回来。
邻居们把她抬上车时,她还在大口大口地吐着鲜血。我没想到她已经病成那样。看着三轮车远去,也绝没有想到那竟是永远的诀别。
邻居的小伙子背着我去看她的时候,她正艰难地呼吸着,像她那一生艰难的生活。别人告诉我,她昏迷前的最后一句话是:“我那个有病的儿子和我那个还未成年的女儿……”
又是秋天,妹妹推着我去北海看了菊花。黄色的花淡雅,白色的花高洁,紫红色的花热烈而深沉,泼泼洒洒,秋风中正开得烂漫。我懂得母亲没有说完的话。妹妹也懂。我俩在一块儿,要好好儿活……
import os

print(os.path.getsize("./fileSave/15_Data.txt"), "B")

sum_size = 0
for file in os.listdir("."):
    if os.path.isfile(file):
        sum_size += os.path.getsize(file)

print(f"all size of dir:{sum_size/1000} KB")
练习题16 : 按文件后缀整理文件夹
1.建个文件夹命名为16_Data,
2.手动创建:
	aaa.txt
	bbb.mp3
	ccc.jpg
	ddd.jpg
	eee.txt
	fff.mp3
	ggg.jpg
	hhh.txt
	iii.mp3
"""
    need:
        1.获取文件的后缀名
            import os
            os.path.splitext('/path/to/aaa.mp3')
                输出:('/path/to/aaa', '.mp3')

        2.移动文件
            import shutil
            shutil.move("aaa.txt","dir/bbb.foo")
"""

import os
import shutil

dir = "fileSave/16_Data"

for file in os.listdir(dir):                # os.listdir() : 获取指定目录下所有内容
    ext = os.path.splitext(file)[1]         # os.path.splitext() : 从后往前搜索".",遇到"."则分割一次
    ext = ext[1:]                           # 去掉 .xxx 中的 "."
    if not os.path.isdir(f"{dir}/{ext}"):   # os.path.isdir() : 判断文件夹是否存在
        os.mkdir(f"{dir}/{ext}")

    source_path = f"{dir}/{file}"
    target_path = f"{dir}/{ext}/{file}"
    shutil.move(source_path, target_path)   # 从旧地址移动到新地址

练习题17 : Python递归搜索目录找出最大的文件
"""
    need:
        1.Python递归搜索目录
            import os
            for root, dirs, files in os.walk('python/Lib/email'):
                # root 表示当前目录
                # dirs 表示当前目录下的子目录
                # files 表示当前目录下的普通文件

"""

import os

search_dir = "D:\softwareCode\00_Code\Python代码\Python练习题"

result_files = []
for root, dirs, files in os.walk(search_dir):
    for file in files:
        if file.endswith(".txt"):  # file.endswith() : 判断字符串是否以指定后缀结尾
            file_path = f'{root}\{file}'
            result_files.append((file_path, str(os.path.getsize(file_path) / 1000) + "KB"))


a = sorted(
    result_files,
    key=lambda x: x[1],
    reverse=True
)[:10]

for i in a:
    print(i)
练习题18 : 计算班级的高分低分平均分
# 18_Data.txt

语文,101,小张,94
语文,102,小王,64
语文,103,小李,62
语文,104,小赵,55
语文,105,小强,91
数学,101,小张,53
数学,102,小王,82
数学,103,小李,86
数学,104,小赵,93
数学,105,小强,72
英语,101,小张,92
英语,102,小王,80
英语,103,小李,73
英语,104,小赵,93
英语,105,小强,51
# key: course, value: grade list
course_grades = {}

with open("fileSave/18_Data.txt", encoding="utf-8") as fin:
    for line in fin:
        line = line[:-1]
        course, son, sname, grade = line.split(",")
        if course not in course_grades:
            course_grades[course] = []
        course_grades[course].append(int(grade))

print(course_grades)

for course, grades in course_grades.items():
    print(
        course,
        max(grades),
        min(grades),
        sum(grades) / len(grades)
    )

练习题19 : Python实现不同文件的关联
# 19_Data_1.txt

语文,101,小张,94
语文,102,小王,64
语文,103,小李,62
语文,104,小赵,55
语文,105,小强,91
数学,101,小张,53
数学,102,小王,82
数学,103,小李,86
数学,104,小赵,93
数学,105,小强,72
英语,101,小张,92
英语,102,小王,80
英语,103,小李,73
英语,104,小赵,93
英语,105,小强,51
# 19_Data_2.txt

语文,于老师
数学,树老师
英语,影老师
course_teacher_map = {}
with open("./fileSave/19_Data_2.txt", encoding="utf-8") as fin:
    for line in fin:
        line = line[:-1]
        course, teahcer = line.split(",")
        course_teacher_map[course] = teahcer


print(course_teacher_map)

with open("./fileSave/19_Data_1.txt", encoding="utf-8") as fin:
    for line in fin:
        line = line[:-1]
        course, sno, sname, sgrade = line.split(",")
        teacher = course_teacher_map.get(course)
        print(course, teacher, sno, sname, sgrade)
练习题20 : Python实现批量txt文件的合并
# 20_Data:文件001.txt

文件001内容-01
文件001内容-02
文件001内容-03
文件001内容-04
文件001内容-05
# 20_Data:文件002.txt

文件002内容-01
文件002内容-02
文件002内容-03
文件002内容-04
文件002内容-05
# 20_Data:文件003.txt

文件003内容-01
文件003内容-02
文件003内容-03
文件003内容-04
文件003内容-05
"""
    need:
        Python读取文件的两个方法
            1.方法一:按行读取
                for line in fin
            2.方法二:一次读取所有内容到一个字符串
                content = fin.read()
"""


import os

data_dir = "./fileSave/20_Data"

contents = []
for file in os.listdir(data_dir):
    file_path = f"{data_dir}/{file}"
    if os.path.isfile(file_path) and file.endswith(".txt"):
        with open(file_path,encoding="utf-8") as fin:
            contents.append(fin.read())

final_content = "n".join(contents)

with open("./fileSave/20_Data/merge.txt", "w", encoding="utf-8") as fout:
    fout.write(final_content)
练习题21 : Python统计每个兴趣的学生人数
# 21_Data.txt

小张 篮球,羽毛球
小王 篮球,乒乓球
小李 篮球,台球
小赵 篮球,足球,台球
小马 乒乓球,台球
小钱 羽毛球,足球
小孙 乒乓球,台球
小强 羽毛球
like_count = {}

with open("./fileSave/21_Data.txt",encoding="utf-8") as fin:
    for line in fin:
        line = line[:-1]
        sname, likes = line.split(" ")
        like_list = likes.split(",")
        for like in like_list:
            if like not in like_count:
                like_count[like] = 0
            like_count[like] += 1

print(like_count)
练习题22 : Python获取当前的日期和时间
import datetime

curr_datetime = datetime.datetime.now()

print(curr_datetime, type(curr_datetime))

# date time to string
str_time = curr_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("str_time", str_time)

print("year", curr_datetime.year)
print("month", curr_datetime.month)
print("day", curr_datetime.day)
print("hour", curr_datetime.hour)
print("minute", curr_datetime.minute)
print("second", curr_datetime.second)
练习题23 : Python计算两个日期相隔的天数
import datetime

birthday = "2001-8-25"
birthady_date = datetime.datetime.strptime(birthday, "%Y-%m-%d")
print(birthady_date, type(birthady_date))

curr_datetime = datetime.datetime.now()
print(curr_datetime, type(curr_datetime))

minus_datetime = curr_datetime - birthady_date
print(minus_datetime, type(minus_datetime))

print(minus_datetime.days)
print(minus_datetime.days / 365)

##练习题24 : Python计算任意日期7天前的日期

import datetime


def get_diff_days(pdate, days):
    pdate_obj = datetime.datetime.strptime(pdate, "%Y-%m-%d")
    time_gap = datetime.timedelta(days=days)
    pdate_result = pdate_obj - time_gap
    return pdate_result.strftime("%Y-%m-%d")


print(get_diff_days("2022-7-21", 1))
print(get_diff_days("2022-7-21", 3))
print(get_diff_days("2022-7-21", 7))
print(get_diff_days("2022-7-01", 3))
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1022436.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号