本文是学习齐老师的《python全栈工程师》课程的笔记,欢迎学习交流。同时感谢齐老师的精彩传授!
习题01.
编写函数,对单词中的字母实现如下操作:
– 根据参数位置,将单词中的字母转化为大写或者小写
– 返回转化之后的单词
def convert(word, low=True):
if low:
return word.lower()
else:
return word.upper()
w = 'Physics'
print(convert(w))
print(convert(w, low=False))
运行效果图:

习题02.
- 编写函数,计算平面直角坐标系中两点的距离,函数的参数是两点的坐标。
- 编写函数,判断某字符串中是否含有指定集合中的字母。
def distance(pa, pb):
import math
lst = [(x-y)**2 for x, y in zip(pa, pb)]
# lst = map(lambda x, y: (x-y)**2, pa, pb)
d = math.sqrt(sum(lst))
return d
pa = (1, 2)
pb = (3, 4)
print('d= ', distance(pa, pb))
运行效果图:
# 编写函数,判断某字符串中是否含有指定集合中的字母。
# 方法一:
def contain_any_1(seq, aset):
for c in seq:
if c in aset:
return True
return False
# 方法二:用filter函数
def contain_any_2(seq, aset):
for i in filter(aset.__contains__, seq):
return True
return False
# 方法三:用集合的交集
def contain_any_3(seq, aset):
return bool(aset.intersection(seq))
seq = 'apython'
aset = set(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'])
result1 = contain_any_1(seq, aset)
result2 = contain_any_2(seq, aset)
result3 = contain_any_3(seq, aset)
print(result1)
print(result2)
print(result3)
运行效果图:
习题03.
- 在字典中有get方法,但是列表中没有。编写函数,对列表实现类似字典中get方法的功能。
# 方法一:下标可能会越界报错,比如列表长度为3,i=-4就报错了
def get_by_index_1(lst, i, value=None):
if i < len(lst):
return lst[i]
else:
return value
# 方法二:
def get_by_index_2(lst, i, value=None):
if -len(lst) <= i < len(lst):
return lst[i]
else:
return value
# 方法三:
def get_by_index_3(lst, i, value=None):
try:
return lst[i]
except IndexError:
return value
lst = [1, 2, 3]
while True:
try:
idx = int(input('input index of list: '))
except ValueError:
print('Index should be int.')
continue
value = input('input value: ')
if value != 'q':
r1 = get_by_index_1(lst, idx, value)
r2 = get_by_index_2(lst, idx, value)
r3 = get_by_index_3(lst, idx, value)
print(r1, r2, r3)
else:
break
运行效果图:(这里我故意输入负数,让方法一报错。哈哈~)
习题04.
- 假设有文件名:py10.py,py2.py,py1.py,py14.py,编写对文件名进行排序的函数
![]()
Python学习笔记:1.4.5 习题课04
import re
def select_numbers(s):
# 正则表达式:此处表示按照整数对字符串 s 进行分割
# re.compile(r'(\d+)') 创建一个正则表达式,表示找出所有的整数
# 相当于 re.split(r'(\d+)', s),以数字为分割符,对 s 进行分割
pieces = re.compile(r'(\d+)').split(s)
# 将数字字符串组成的列表,转换成整数数字的列表
pieces[1::2] = map(int, pieces[1::2])
return pieces
def sort_filename(filename):
return sorted(filename, key=select_numbers)
files = ['py10.py', 'py2.py', 'py1.py', 'py14.py']
result = sort_filename(files)
print(files)
print(result)
运行效果图:
补充知识:sorted函数
注意函数的另外一种写法:
# 这里的:int表示参数的类型,-> int表示函数返回值的类型,
# 但是这些是给人看的,对python解析器来说,跟不写没什么两样
def add(x:int, y:int) -> int:
return x + y
s = add(2, 3)
print(s) # 5
s2 = add('hello', 'world') # 虽然定义int类型,传字符串依然可以。所以那样写没啥用,哈哈
print(s2) # helloworld
# 以上函数跟下面函数相同
def add(x, y):
return x + y