Python编程实践与数据结构练习

内容分享3小时前发布
0 0 0

table {
border-collapse: collapse;
width: 100%;
margin-bottom: 1rem;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
pre {
background-color: #f8f8f8;
padding: 15px;
border-radius: 4px;
overflow-x: auto;
}

1、在Python shell中,输入字符串 “ Rock a by baby,on the tree top,when the wind blows the cradle will drop. ” 。可以随意尝试不同数量的转义序列,看看这会如何影响屏幕上的显示,甚至可以尝试改变它们的位置。你认为输入含有转义序列的字符串后在屏幕上可能会看到什么?

由于没有使用

print()

函数打印,特殊字符(那些前面带有反斜杠的字符)不会被转换为与输入时不同的显示形式,会按原样显示。

2、在Python shell中,使用一个指定的字符串,使用print()函数显示它。尝试改变字符串中转义序列的数量,观察会有什么不同。

当使用

print()

函数时,

"
"


" "

分别会产生换行符和制表符,函数会将它们渲染成键盘上没有的特殊字符并显示在屏幕上;而不使用

print()

函数时,特殊字符(那些前面带有反斜杠的字符)不会被转换为与输入不同的显示形式。

3、在Python shell中,计算5乘以10。也用其他数字进行同样的尝试。

在Python shell中,计算5乘以10可以输入

5 * 10

,结果为50。用其他数字尝试,例如计算3乘以7,可输入

3 * 7

,结果为21。

4、打印从6到14的每个数字的八进制表示。


print('%o' % 6)
print('%o' % 7)
print('%o' % 8)
print('%o' % 9)
print('%o' % 10)
print('%o' % 11)
print('%o' % 12)
print('%o' % 13)
print('%o' % 14)

5、以十六进制形式打印从9到19的每个数字。

在Python中可以使用如下代码实现:


for num in range(9, 20):
    print(hex(num))

运行代码后,会输出从9到19对应的十六进制表示。

6、尝试从 Python 解释器中引出错误,例如故意将 print 拼写错误为 pinrt,会发生什么情况?同时说明在 Python shell 中 print 和 pinrt 显示方式的不同。

当故意将

print

拼写为

pinrt

时,Python 解释器会抛出

NameError

异常,提示

'name 'pinrt' is not defined'

,因为 Python 解释器找不到名为

pinrt

的函数。在 Python shell 中,正确的

print

通常会以特定颜色(如蓝色)高亮显示,表明它是 Python 的内置函数;而错误拼写的

pinrt

不会有这种高亮效果,一般以普通文本颜色显示。

7、创建一个名为dairy_section的列表,包含超市乳制品区的四个元素。


dairy_section = ['milk', 'cottage cheese', 'butter', 'yogurt']

8、创建一个名为 milk_expiration 的元组,包含三个元素:最近一盒牛奶的过期日期的月、日和年。

milk_expiration = (10, 10, 2009)

9、以“ This milk carton will expire on 12/10/2009. ”这样的字符串形式打印出

milk_expiration

元组中的值。


>>> print('This milk carton will expire on %d/%d/%d' % (milk_expiration[0], milk_expiration[1], milk_expiration[2]))

10、创建一个名为 milk_carton 的空字典。添加以下键/值对:键 ‘expiration_date’ 的值为一个元组(可自行编造元组内容代表牛奶的过期日期),键 ‘fl_oz’ 的值为牛奶盒的容量(可自行设定数值),键 ‘Cost’ 的值为这盒牛奶的成本(可自行设定数值),键 ‘brand_name’ 的值为牛奶品牌名称(可自行设定名称)。


milk_carton = {}
milk_carton['expiration_date'] = (2024, 10, 1)
milk_carton['fl_oz'] = 32
milk_carton['Cost'] = 1.50
milk_carton['brand_name'] = 'Milk'

11、假设存在一个名为

milk_carton

的字典,使用该字典中的值,打印出

milk_carton

中所有元素的值。


print("The expiration date is %d/%d/%d" % (milk_carton["expiration_date"][0], milk_carton["expiration_date"][1], milk_carton["expiration_date"][2]))

12、已知一个名为 milk_carton 的数据结构中存储了牛奶的单价信息,展示如何计算六盒牛奶的成本。

可以使用代码

print("The cost for 6 cartons of milk is %.02f" % (6 * milk_carton["cost"]))

来计算并输出六盒牛奶的成本,示例中六盒牛奶成本为

9.00

13、创建一个名为 cheeses 的列表,列出你能想到的所有奶酪。将这个列表追加到 dairy_section 列表中,查看 dairy_section 的内容。然后从该列表中移除 cheeses 列表。


cheeses = ['cheddar', 'american', 'mozzarella']
dairy_section = ['milk', 'cottage cheese', 'butter', 'yogurt']
dairy_section.append(cheeses)
print(dairy_section)
removed_cheeses = dairy_section.pop()
print(removed_cheeses)

14、如何计算奶酪列表中奶酪的数量?

可以使用

len()

函数来计算。在示例代码中,使用

len(cheeses)

即可得到奶酪列表中奶酪的数量。

15、使用一系列

if ... :

语句,通过创建五个单独的测试来评估从 0 到 4 的数字是

True

还是

False


在 Python 中,除了 0 被视为

False

,其他非零数字都被视为

True

。以下是实现该功能的代码示例:


num = 0
if num:
    print(f'{num} 为 True')
else:
    print(f'{num} 为 False')

num = 1
if num:
    print(f'{num} 为 True')
else:
    print(f'{num} 为 False')

num = 2
if num:
    print(f'{num} 为 True')
else:
    print(f'{num} 为 False')

num = 3
if num:
    print(f'{num} 为 True')
else:
    print(f'{num} 为 False')

num = 4
if num:
    print(f'{num} 为 True')
else:
    print(f'{num} 为 False')

16、使用单条 if…: 语句创建一个测试,判断一个值是否在 0 到 9(包含 0 和 9)的范围内。如果满足条件,则打印一条消息。并对其进行测试。

以下是满足要求的 Python 代码示例:


value = 5 # 可修改此值进行测试
if 0 <= value <= 9:
    print('该值在 0 到 9 范围内。')

17、创建一个名为 fridge 的字典,用于表示一个想象中的冰箱,食物名称作为键,每个食物项对应的描述作为值。然后创建一个名为 food_sought 的变量,它指向一个包含食物名称的字符串。使用 for…in… 循环对冰箱字典中的每个键进行简单的 if…: 测试(不需要 elif…: 或 else:)。如果找到匹配项,打印包含键和值的消息,然后使用 break 跳出循环。在 for 循环结束时使用 else…: 语句,为未找到元素的情况打印一条消息。

以下是实现该需求的 Python 代码示例:


# 创建冰箱字典
fridge = {
    '苹果': '红色的水果',
    '香蕉': '黄色的长条形水果',
    '牛奶': '白色的饮品'
}

# 创建要查找的食物名称
food_sought = '香蕉'

# 遍历冰箱中的每个键
for key in fridge:
    if key == food_sought:
        print(f'找到 {key},描述为:{fridge[key]}')
        break
else:
    print(f'未找到 {food_sought}')

18、编写一个名为 do_plus 的函数,该函数接受两个参数,并使用“ + ”运算符将它们相加。

以下是实现该功能的 Python 代码:


def do_plus(a, b):
    return a + b

19、添加类型检查以确认参数的类型是整数或字符串。如果参数不符合要求,则抛出一个类型错误(TypeError)。

以下是实现该功能的 Python 代码示例:


def do_plus(param1, param2):
    if not (isinstance(param1, (int, str)) and isinstance(param2, (int, str))):
        raise TypeError("参数必须是整数或字符串类型。")
    return param1 + param2

20、创建一个可以被煎蛋卷类调用以获取食材的食谱类。该食谱类应包含煎蛋卷类中已有的相同煎蛋卷的食材列表。你也可以根据需要包含其他食物。食谱类应包含检索食谱的方法get(recipe_name),以及添加食谱并命名的方法create(recipe_name, ingredients),其中食材是一个字典。

以下是满足需求的

Recipe

类代码:


class Recipe:
    def __init__(self):
        self.set_default_recipes()

    def set_default_recipes(self):
        self.recipes = {
            'cheese': {'eggs': 2, 'milk': 1, 'cheese': 1},
            'mushroom': {'eggs': 2, 'milk': 1, 'cheese': 1, 'mushroom': 2},
            'onion': {'eggs': 2, 'milk': 1, 'cheese': 1, 'onion': 1}
        }

    def get(self, name):
        try:
            recipe = self.recipes[name]
            return recipe
        except KeyError:
            return False

    def create(self, name, ingredients):
        self.recipes[name] = ingredients

21、为Foods.Recipe模块编写一个测试,该测试使用一个食物列表创建一个食谱对象,然后验证所提供的键和值是否都存在且匹配。编写该测试,使其仅在直接调用Recipe.py时运行,而在导入时不运行。


if __name__ == '__main__':
    r = Recipe()
    if r.recipes != {"cheese": {"eggs": 2, "milk": 1, "cheese": 1}, "mushroom": {"eggs": 2, "milk": 1, "cheese": 1, "mushroom": 2}, "onion": {"eggs": 2, "milk": 1, "cheese": 1, "onion": 1}}:
        print("Failed: the default recipes is not the correct list")
    cheese_omelet = r.get("cheese")
    if cheese_omelet != {"eggs": 2, "milk": 1, "cheese": 1}:
        print("Failed: the ingredients for a cheese omelet are wrong")
    western_ingredients = {"eggs": 2, "milk": 1, "cheese": 1, "ham": 1, "peppers": 1, "onion": 1}
    r.create("western", western_ingredients)
    if r.get("western") != western_ingredients:
        print("Failed to set the ingredients for the western")
    else:
        print("Succeeded in getting the ingredients for the western.")

22、为Foods.Fridge模块编写一个测试,该测试将向Fridge中添加物品,并测试除get_ingredients之外的所有接口,因为get_ingredients需要一个Omelet对象。

在Fridge模块的末尾插入以下代码:

注意关于将

add_many

函数修改为返回

True

的注释。如果不这样做,

add_many

将返回

None

,此测试将始终失败!


if __name__ == '__main__':
    f = Fridge({"eggs":10, "soda":9, "nutella":2})
    if f.has("eggs") != True:

23、创建另一个版本的(非递归)

print_dir

函数,该函数先列出所有子目录名,然后列出目录中的文件名。子目录名和文件名都应按字母顺序排列。(额外加分:以只调用一次

os.listdir

的方式编写函数。Python 处理字符串的速度比执行

os.listdir

更快。)


import os

def print_dir(dir_path):
    # 循环遍历目录条目。由于我们先对组合的目录条目进行排序,
    # 子目录名和文件名也会分别排序。
    file_names = []
    for name in sorted(os.listdir(dir_path)):
        full_path = os.path.join(dir_path, name)
        if os.path.isdir(full_path):
            # 现在打印子目录名。
            print(full_path)
        elif os.path.isfile(full_path):
            # 存储文件名以供后续使用。
            file_names.append(full_path)
    # 现在打印文件名。
    for name in file_names:
        print(name)

24、请将英文句子“Chapter 9 is a grab – bag of different features. At this point, the best exercise is to test all of the sample code, looking at the output produced and trying to picture how the various ideas introduced here could be used to solve problems that you ’ d like to solve or would have liked to solve in the past.”翻译成中文。

第9章

第9章涵盖了各种各样的特性。在这一点上,最好的练习方法是测试所有示例代码,查看所产生的输出,并尝试设想这里引入的各种概念如何能够用于解决你现在想解决或者过去想解决的问题。

25、如何访问模块提供的功能?

可以通过导入模块或从模块中导入项目来访问模块提供的功能。

26、如何控制模块中的哪些项被视为公共项?(公共项可供其他 Python 脚本使用。)

如果定义变量

__all__

,可以列出构成模块公共 API 的项。例如:


__all__ = ['Meal', 'AngryChefException', 'makeBreakfast', 'makeLunch', 'makeDinner', 'Breakfast', 'Lunch', 'Dinner']

如果未定义

__all__

变量,Python 解释器会查找所有名称不以下划线开头的项。

27、如何查看系统上安装了哪些模块?

sys.modules

字典会显示所有已调用的模块。对于未显式导入的模块,可以认为是 Python 自动调用以处理操作系统等相关机制。

28、你可以在模块中放置哪种 Python 命令?

可以在模块中放置任何 Python 命令,包括语句、函数、变量、类等。不过,大多数情况下应避免在模块中运行命令,而应定义函数和类,让调用者决定调用什么。

29、修改

scan_pdy.py

脚本,使其仅匹配文件名中包含文本

boobah

的 PDF 文件。


import os
import re


def print_pdf(arg, dir, files):
    for file in files:
        path = os.path.join(dir, file)
        path = os.path.normcase(path)
        if not re.search(r'.*.pdf', path):
            continue
        if not re.search(r'boobah', path):
            continue
        print(path)


os.path.walk('.', print_pdf, 0)

30、修改 scan_pdf.py 脚本,排除文件名中包含文本 boobah 的所有文件。


import os
import re

def print_pdf(arg, dir, files):
    for file in files:
        path = os.path.join(dir, file)
        path = os.path.normcase(path)
        if not re.search(r'.*.pdf', path):
            continue
        if re.search(r'boobah', path):
            continue
        print(path)

os.path.walk('.', print_pdf, 0)

31、通过更改每个属性来练习修改小部件的外观。

修改小部件外观的属性

可以修改以下属性来改变小部件外观:


边框(Border)和边框样式(relief)



Border

可设置边框宽度(如

bd = 1




Relief

用于确定边框样式(如

relief = raised


颜色(Color)



bg

设置背景颜色


fg

设置前景颜色

– 可使用简单颜色名称或十六进制颜色代码


光标(Cursor)


– 设置鼠标悬停在小部件上时显示的光标类型(如

cursor = cross


字体(Font)


– 可设置字体家族、大小和样式(如

Times, 24, italic bold underline


内边距(Padding)


– 设置小部件周围的额外空间


布局扩展和填充(Pack expand and fill)


状态(State)


– 设置对象的状态(如

state = DISABLED


大小(Size)


– 通过高度和宽度设置控制小部件的大小

示例代码


import tkinter
from tkinter import *

root = Tk()
labelfont = ('times', 24, 'italic')
widget = Label(root, text='Eat At JOES')
widget.config(bg='black', fg='red')
widget.pack(expand=YES, fill=BOTH)
root.mainloop()

可在代码基础上修改各属性观察效果。

32、假设你需要编写一个 Python 脚本,来存储你所在部门员工的披萨偏好。你需要存储每个人的姓名以及他们最喜欢的披萨配料。实现此脚本最适合使用哪些技术?a. 设置一个关系型数据库,如 MySQL 或 Sqlite。b. 使用一个 dbm 模块,如 dbm。c. 实现一个由 Web 服务支持的富 Web 应用程序,以创建一个符合流行术语的应用程序。

a

33、使用表名别名重写以下示例查询:select employee.firstname, employee.lastname, department.name from employee, department where employee.dept = department.departmentid order by employee.lastname desc


select e.firstname, e.lastname, d.name 
from employee e, department d 
where e.dept = d.departmentid 
order by e.lastname desc

34、之前展示的terminate.py脚本会从employee表中删除一条员工记录,但该脚本并不完整,user表中仍保留着同一人的记录。请修改terminate.py脚本,使其能删除该用户在employee表和user表中的记录。

修改后的脚本如下:


import sys
import sqlite3

conn = sqlite3.connect('sample_database')
cursor = conn.cursor()
employee = sys.argv[1]

# 查询员工ID
query = """select e.empid
from user u, employee e where username=? and u.employeeid = e.empid"""
cursor.execute(query, (employee,))
empid = None
for row in cursor.fetchone(): 
    if (row != None): 
        empid = row

if empid:
    # 删除employee表中的记录 
    cursor.execute("delete from employee where empid=?", (empid,)) 
    # 删除user表中的记录 
    cursor.execute("delete from user where employeeid=?", (empid,)) 
    conn.commit()

cursor.close()
conn.close()

运行此脚本时,需要传入要删除的用户的用户名。若脚本未出错,则不会有输出。

© 版权声明

相关文章

暂无评论

none
暂无评论...