Skip to content

Commit 77d6b68

Browse files
committed
习题
更新答案
1 parent 49a1570 commit 77d6b68

File tree

4 files changed

+158
-0
lines changed

4 files changed

+158
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# 练习一 定义装饰器,用于打印函数执行的时间
2+
1. 统计函数开始执行和结束执行的时间
3+
2. 扩展练习:为装饰器传入超时时间,函数执行超过指定时间后退出
4+
```python
5+
# 为装饰器传入超时时间,函数执行超过指定时间后退出
6+
# windows下signal.SIGALRM不可用
7+
8+
import time
9+
import signal
10+
11+
12+
def timeout(seconds=10, error_message="Timer expired"):
13+
def decorator(func):
14+
def handler(singnum, frame):
15+
raise TimeoutError(error_message)
16+
17+
def wrapper(*args, **kwargs):
18+
signal.signal(signal.SIGALRM, handler)
19+
signal.alarm(seconds)
20+
try:
21+
result = func(*args, **kwargs)
22+
finally:
23+
signal.alarm(0)
24+
return result
25+
return wrapper
26+
return decorator
27+
28+
29+
@timeout(5)
30+
def getinfo(msg):
31+
print("getinfo start!")
32+
print("msg: %s" % msg)
33+
time.sleep(10)
34+
print("getinfo end!")
35+
return 1
36+
37+
38+
if __name__ == '__main__':
39+
try:
40+
getinfo('Test!')
41+
except TimeoutError as e:
42+
print("time out: %s" % e)
43+
44+
```
45+
46+
47+
# 练习二 定义装饰器,实现不同颜色显示执行结果的功能
48+
```python
49+
# 1. 向装饰器传递参数,通过传递的参数获取到输出的颜色
50+
# 2. 被装饰函数的print( )输出根据装饰器得到的颜色进行输出
51+
import sys
52+
53+
54+
def make_color(code):
55+
def decorator(func):
56+
def color_func(s):
57+
if not sys.stdout.isatty():
58+
return func(s)
59+
tpl = '\x1b[{}m{}\x1b[0m'
60+
return tpl.format(code, func(s))
61+
return color_func
62+
return decorator
63+
64+
65+
@make_color(33)
66+
def fmta(s):
67+
return '{:^7}'.format(str(float(s) * 1000)[:5] + 'ms')
68+
69+
```
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# 练习一 文件的创建和使用
2+
```python
3+
# 1. 创建一个文件,并写入当前日期
4+
import datetime
5+
now = datetime.datetime.now()
6+
with open('c.txt', 'w') as f:
7+
# 注意write( )方法写入的内容是字符串类型
8+
f.write(str(now))
9+
10+
11+
# 2. 再次打开这个文件,读取文件的前4个字符后退出
12+
with open('c.txt', 'r') as f:
13+
text_4 = f.read(4)
14+
print(text_4)
15+
```
16+
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# 练习一 异常
2+
```python
3+
# 1. 在Python程序中,分别使用未定义变量、访问列表不存在的索引、访问字典不存在的关键字观察系统提示的错误信息
4+
5+
# 使用未定义变量
6+
a + 1
7+
8+
# 访问列表不存在的索引
9+
b = ['a', 'b', 'c']
10+
b[3]
11+
12+
# 访问字典不存在的key
13+
c = {'x': 1}
14+
c['y']
15+
16+
17+
# 2. 通过Python程序产生IndexError,并用try捕获异常处理
18+
try:
19+
b = ['a', 'b', 'c']
20+
b[3]
21+
except IndexError:
22+
print('访问列表不存在的索引')
23+
24+
```

exercise/9 函数/answer/README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# 练习一 函数
2+
```python
3+
# 1. 创建一个函数,用于接收用户输入的数字,并计算用户输入数字的和
4+
def func1():
5+
two_num = input('请输入两个数字,用空格做分隔:')
6+
# 检查用户输入是否合法
7+
func2(two_num)
8+
num1, *_, num2 = list(two_num)
9+
print(int(num1) + int(num2))
10+
11+
12+
def func2(check_number):
13+
pass
14+
15+
16+
func1()
17+
18+
19+
# 2. 创建一个函数,传入n个整数,返回其中最大的数和最小的数
20+
21+
22+
def func3(*nums):
23+
print(max(list(nums)))
24+
print(min(list(nums)))
25+
26+
27+
func3(1, 5, 8, 32, 654, 765, 4, 6, 7)
28+
29+
30+
# 3. 创建一个函数,传入一个参数n,返回n的阶乘
31+
32+
33+
def fact(num3):
34+
if num3 == 0 or num3 == 1:
35+
return 1
36+
else:
37+
return (num3 * fact(num3 - 1))
38+
39+
40+
print(fact(10))
41+
42+
43+
# 使用高阶函数
44+
from functools import reduce
45+
num4 = 10
46+
print(reduce(lambda x, y: x * y, range(1, num4 + 1)))
47+
48+
```
49+

0 commit comments

Comments
 (0)