提交 07c57b6c 编写于 作者: F feilong

改进13-19题

上级 447a383d
{
"source": "call.py",
"source": "call.md",
"depends": [],
"exercise_id": 197,
"type": "code_options"
......
# 基于函数的API设计,理解接口与实现分离
使用函数设计一组 “容器API”:init/set/get/exist,用例如下:
```python
def init():
# TODO(You): 实现初始化
def set(dict, key, value):
# TODO(You): 实现初始化
def get(dict, key):
# TODO(You): 实现获取接口
def exist(dict, key):
# TODO(You): 实现判断接口
if __name__ == '__main__':
dict = init()
for i in range(10):
key = "key_{}".format(i)
value = i
set(dict, key, value)
test_key = "key_4"
if exist(dict, test_key):
test_value = get(dict, test_key)
print("key is: {}, value is: {}".format(test_key, test_value))
```
请选出下面对`TODO`方法的实现代码中,<span style="color:red">错误</span> 的实现。
## template
```python
def init():
return {}
def set(dict, key, value):
dict[key] = value
def get(dict, key):
return dict.get(key)
def exist(dict, key):
return dict.get(key) is not None
if __name__ == '__main__':
dict = init()
for i in range(10):
key = "key_{}".format(i)
value = i
set(dict, key, value)
test_key = "key_4"
if exist(dict, test_key):
test_value = get(dict, test_key)
print("key is: {}, value is: {}".format(test_key, test_value))
```
## 答案
```python
def init():
return {"pre": None, "key": None, "value": None, "next": None}
def set(dict, key, value):
node = dict
while node is not None:
if node['key'] == key:
return
node = node['next']
node['next'] = {"pre": node, "key": key, "value": value, "next": None}
def get(dict, key):
node = dict
while node is not None:
if node['key'] == key:
return node['value']
node = node['next']
def exist(dict, key):
node = dict
while node is not None:
if node['key'] == key:
return True
node = node['next']
return False
```
## 选项
### A
```python
def init():
return []
def set(dict, key, value):
if not key in dict or dict.index(key) % 2 != 0:
dict.append(key)
dict.append(value)
def get(dict, key):
if key in dict:
pos = dict.index(key)
if pos % 2 == 0:
return dict[pos+1]
return None
def exist(dict, key):
return key in dict and dict.index(key) % 2 == 0
```
### B
```python
def init():
return [], []
def set(dict, key, value):
keys, values = dict
if not key in keys:
keys.append(key)
values.append(value)
def get(dict, key):
keys, values = dict
if not key in keys:
return None
else:
return values[keys.index(key)]
def exist(dict, key):
keys, values = dict
return key in keys
```
### C
```python
def init():
return {}
def set(dict, key, value):
dict[key] = value
def get(dict, key):
return dict.get(key)
def exist(dict, key):
return dict.get(key) is not None
```
......@@ -3,23 +3,96 @@
# 标题:Python 函数调用
# 描述:使用函数设计一组 “容器API”:init/set/get/exist
# def init():
# return {}
# def set(dict, key, value):
# dict[key] = value
# def get(dict, key):
# return dict.get(key)
# def exist(dict, key):
# return dict.get(key) is not None
# def init():
# return [], []
# def set(dict, key, value):
# keys, values = dict
# if not key in keys:
# keys.append(key)
# values.append(value)
# def get(dict, key):
# keys, values = dict
# if not key in keys:
# return None
# else:
# return values[keys.index(key)]
# def exist(dict, key):
# keys, values = dict
# return key in keys
# def init():
# return []
# def set(dict, key, value):
# if not key in dict or dict.index(key) % 2 != 0:
# dict.append(key)
# dict.append(value)
# def get(dict, key):
# if key in dict:
# pos = dict.index(key)
# if pos % 2 == 0:
# return dict[pos+1]
# return None
# def exist(dict, key):
# return key in dict and dict.index(key) % 2 == 0
def init():
return {}
return {"pre": None, "key": None, "value": None, "next": None}
def set(dict, key, value):
dict[key] = value
node = dict
while node is not None:
if node['key'] == key:
return
last = node
node = node['next']
last['next'] = {"pre": last, "key": key, "value": value, "next": None}
def get(dict, key):
return dict.get(key)
node = dict
while node is not None:
if node['key'] == key:
return node['value']
node = node['next']
def exist(dict, key):
return dict.get(key) is not None
node = dict
while node is not None:
if node['key'] == key:
return True
node = node['next']
return False
def test():
if __name__ == '__main__':
dict = init()
for i in range(10):
key = "key_{}".format(i)
......@@ -30,7 +103,3 @@ def test():
if exist(dict, test_key):
test_value = get(dict, test_key)
print("key is: {}, value is: {}".format(test_key, test_value))
if __name__ == '__main__':
test()
{
"source": "fact1.py",
"source": "fact1.md",
"depends": [],
"exercise_id": 190,
"type": "code_options"
......
# 循环计算阶乘函数
0,1,2,3,4,5,6,7,8,9,10! 令人惊讶的是,6个星期的秒数居然也等于10!
不使用函数递归,实现一个阶乘计算函数(n<=170):
```python
def fact(n):
r = 1
# TODO(You): 请在此编写代码
return r
if __name__ == '__main__':
print(fact(10))
```
请选出下面的 Python 非递归阶乘实现代码中,<span style="color:red">错误</span> 的选项。
## template
```python
def fact1(n):
r = 1
for i in range(0, n):
r *= (i+1)
return r
def fact2(n):
r = 1
while (n > 0):
r *= n
n -= 1
return r
def fact3(op):
import math
z = op + 1
p = [1.000000000190015, 76.18009172947146, -86.50532032941677,
24.01409824083091, -1.231739572450155, 1.208650973866179E-3, -5.395239384953E-6]
d1 = math.sqrt(2 * math.pi) / z
i = 1
d2 = p[0]
while i <= 6:
d2 += p[i] / (z + i)
i += 1
d3d4 = math.pow((z + 5.5), (z + 0.5))*math.exp(-(z + 5.5))
d = d1 * d2 * d3d4
return int(d)
def fact4(n):
import math
r = math.factorial(n)
return r
if __name__ == '__main__':
print(fact1(10))
print(fact2(24))
print(fact3(24))
print(fact4(10))
```
## 答案
```python
import math
z = n + 1
p = [1.000000000190015, 76.18009172947146, -86.50532032941677,
24.01409824083091, -1.231739572450155, 1.208650973866179E-3, -5.395239384953E-6]
d1 = math.sqrt(2 * math.pi) / z
i = 1
d2 = p[0]
while i <= 6:
d2 += p[i] / (z + i)
i += 1
d3d4 = math.pow((z + 5.5), (z + 0.5))*math.exp(-(z + 5.5))
d = d1 * d2 * d3d4
r = int(d)
```
## 选项
### A
```python
for i in range(0, n):
r *= (i+1)
```
### B
```python
while n > 0:
r *= n
n -= 1
```
### C
```python
import math
r = math.factorial(n)
```
......@@ -3,12 +3,48 @@
# 标题:Python 函数
# 描述:循环计算阶乘函数
def fact(n):
sum = 1
def fact1(n):
r = 1
for i in range(0, n):
sum *= (i+1)
return sum
r *= (i+1)
return r
def fact2(n):
r = 1
while (n > 0):
r *= n
n -= 1
return r
def fact3(op):
import math
z = op + 1
p = [1.000000000190015, 76.18009172947146, -86.50532032941677,
24.01409824083091, -1.231739572450155, 1.208650973866179E-3, -5.395239384953E-6]
d1 = math.sqrt(2 * math.pi) / z
i = 1
d2 = p[0]
while i <= 6:
d2 += p[i] / (z + i)
i += 1
d3d4 = math.pow((z + 5.5), (z + 0.5))*math.exp(-(z + 5.5))
d = d1 * d2 * d3d4
return int(d)
def fact4(n):
import math
r = math.factorial(n)
return r
if __name__ == '__main__':
print(fact(10))
print(fact1(10))
print(fact2(24))
print(fact3(24))
print(fact4(10))
{
"source": "fact2.py",
"source": "fact2.md",
"depends": [],
"exercise_id": 244,
"type": "code_options"
......
# Python 函数递归(1)
使用函数递归的方式可以方便的写出阶乘计算。
```python
# TODO(You): 请实现递归计算阶乘
if __name__ == '__main__':
print(fact(998))
```
请选出下面的 Python 递归阶乘实现代码中,<span style="color:red">错误</span> 的选项。
## template
```python
def fact(n):
if n == 1:
return 1
return n*fact(n-1)
if __name__ == '__main__':
print(fact(998))
```
## 答案
```python
def inner_fact(n, m, r):
if m == n:
return r
return inner_fact(n, m+1, r*m)
def fact4(n):
return inner_fact(n, 1, 1)
```
## 选项
### A
```python
def fact(n):
if n == 1:
return 1
return n*fact(n-1)
```
### B
```python
def inner_fact(n, r):
if n == 1:
return r
return inner_fact(n-1, r*n)
def fact(n):
return inner_fact(n, 1)
```
### C
```python
def inner_fact(n, m):
if m == n:
return n
return m*inner_fact(n, m+1)
def fact(n):
return inner_fact(n,1)
```
......@@ -3,11 +3,48 @@
# 标题:Python 函数递归
# 描述:递归计算阶乘函数
def fact(n):
import math
import sys
def fact1(n):
if n == 1:
return 1
return n*fact(n-1)
return n*fact1(n-1)
def inner_fact_2(n, r):
if n == 1:
return r
return inner_fact_2(n-1, r*n)
def fact2(n):
return inner_fact_2(n, 1)
def inner_fact3(n, m):
if m == n:
return n
return m*inner_fact3(n, m+1)
def fact3(n):
return inner_fact3(n, 1)
def inner_fact_4(n, m, r):
if m == n:
return r*n
return inner_fact_4(n, m+1, r*m)
def fact4(n):
return inner_fact_4(n, 1, 1)
if __name__ == '__main__':
print(fact(998))
print(fact1(100))
print(fact2(100))
print(fact3(100))
print(fact4(100))
{
"source": "fibonacci1.py",
"source": "fibonacci1.md",
"depends": [],
"exercise_id": 201,
"type": "code_options"
......
# Python 斐波那契(fibonacci)(I)
数学家莱昂纳多·斐波那契(Leonardo Fibonacci)以兔子繁殖为例子引入了数列0、1、1、2、3、5、8、13、21、34...,称为斐波那契数列(Fibonacci sequence),又称“黄金分割数列”或者“兔子数列”。使用函数递归或非递归的方式都可以方便地计算斐波那契函数:F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2)
```python
# TODO(You): 请实现递归计算斐波那契函数
if __name__ == '__main__':
print(fibonacci(6))
```
请选出下面的 Python 斐波那契实现代码中,<span style="color:red">错误</span> 的选项。
## template
```python
def fibonacci(n):
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
if __name__ == '__main__':
print(fibonacci(6))
```
## 答案
```python
def fibonacci_inner(n, r):
if n == 1 or n == 2:
return r
return fibonacci_inner(n-1, fibonacci_inner(n-2, r))
def fibonacci4(n):
return fibonacci_inner(n, 0)
```
## 选项
### A
```python
def fibonacci(n):
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
```
### B
```python
def fibonacci(n):
if n == 1 or n == 2:
return 1
r = [1, 1]
for i in range(2, n):
r[1],r[0] = r[1]+r[0],r[1]
return r[1]
```
### C
```python
def fibonacci_inner(n, m, r0, r1):
if m == n:
return r1
return fibonacci_inner(n, m+1, r1, r0+r1)
def fibonacci(n):
return fibonacci_inner(n, 2, 1, 1)
```
### D
```python
def fibonacci(n):
from math import pow, sqrt
return int(1/sqrt(5)*(pow((1+sqrt(5))/2, n)-pow((1-sqrt(5))/2, n)))
```
......@@ -3,12 +3,57 @@
# 标题:Python 函数递归
# 描述:递归计算斐波那契函数
def fibonacci(n):
from typing_extensions import runtime
def fibonacci1(n):
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
return fibonacci1(n-1) + fibonacci1(n-2)
def fibonacci2(n):
if n == 1 or n == 2:
return 1
r = [1, 1]
for i in range(2, n):
r[1], r[0] = r[1]+r[0], r[1]
return r[1]
def fibonacci_inner3(n, m, r0, r1):
if m == n:
return r1
return fibonacci_inner3(n, m+1, r1, r0+r1)
def fibonacci3(n):
return fibonacci_inner3(n, 2, 1, 1)
def fibonacci_inner4(n, r):
if n == 1 or n == 2:
return r
return fibonacci_inner4(n-1, fibonacci_inner4(n-2, r))
def fibonacci4(n):
return fibonacci_inner4(n, 0)
def fibonacci5(n):
from math import pow, sqrt
return int(1/sqrt(5)*(pow((1+sqrt(5))/2, n)-pow((1-sqrt(5))/2, n)))
if __name__ == '__main__':
print(fibonacci(6))
print(fibonacci1(20))
print(fibonacci2(20))
print(fibonacci3(20))
print(fibonacci4(20))
print(fibonacci5(20))
{
"source": "fibonacci2.py",
"source": "fibonacci2.md",
"depends": [],
"exercise_id": 239,
"type": "code_options"
......
# Python 斐波那契(fibonacci)(II)
斐波那契的递归实现版本里面有很多冗余计算,可以通过增加缓存来优化。
```python
def fibonacci_inner(n, cache):
if n == 1 or n == 2:
return 1
r = 0
# TODO(You): 实现缓存
def fibonacci(n):
return fibonacci_inner(n, {})
if __name__ == '__main__':
print(fibonacci(6))
```
请选出下面的 Python 斐波那契的缓存优化实现代码中,<span style="color:red">错误</span> 的选项。
## template
```python
def fibonacci_inner1(n, cache):
if n == 1 or n == 2:
cache[0] = 1
cache[1] = 1
return 1
if cache.get(n) is None:
fibonacci_inner1(n-2, cache)
fibonacci_inner1(n-1, cache)
cache[n-1] = cache[n-2]+cache[n-3]
return cache[n-1]
def fibonacci1(n):
return fibonacci_inner1(n, {})
if __name__ == '__main__':
print(fibonacci1(10))
```
## 答案
```python
if cache.get(n) is None:
fibonacci_inner1(n-2, cache)
fibonacci_inner1(n-1, cache)
cache[n] = cache[n-1]+cache[n-2]
return cache[n]
```
## 选项
### A
```python
if cache.get(n) is None:
cache[n-2] = fibonacci_inner1(n-2, cache)
cache[n-1] = fibonacci_inner1(n-1, cache)
cache[n] = cache[n-1]+cache[n-2]
return cache[n]
```
### B
```python
if cache.get(n) is not None:
return cache[n]
else:
cache[n] = fibonacci_inner1(n-1, cache) + fibonacci_inner1(n-2, cache)
return cache[n]
```
### C
```python
if cache.get(n) is None:
cache[n] = fibonacci_inner(n-2, cache) + fibonacci_inner(n-3, cache)
return cache[n]
```
......@@ -3,17 +3,23 @@
# 标题:Python 函数+缓存
# 描述:递归计算斐波那契函数, 带缓存
def fibonacci(n, cache):
def fibonacci_inner1(n, cache):
if n == 1 or n == 2:
cache[0] = 1
cache[1] = 1
return 1
if cache.get(n) is not None:
return cache[n]
if cache.get(n) is None:
fibonacci_inner1(n-2, cache)
fibonacci_inner1(n-1, cache)
cache[n-1] = cache[n-2]+cache[n-3]
cache[n] = fibonacci(n-1, cache) + fibonacci(n-2, cache)
return cache[n-1]
return cache[n]
def fibonacci1(n):
return fibonacci_inner1(n, {})
if __name__ == '__main__':
print(fibonacci(6, {}))
print(fibonacci1(10))
{
"one_line": {
"circulate_print(str, count+1)": [
"circulate_print(str, count)"
],
"if count == 5": [
"if count > 5"
],
"count=0": [
"count"
]
},
"source": "helloworld2.py",
"source": "helloworld2.md",
"depends": [],
"exercise_id": 166,
"type": "code_options"
......
# 使用函数组织代码
函数是代码复用的最简单形式。在第一章里我们已经多次不经介绍地使用了函数来组织代码。现在可以系统认识下函数的参数。
```python
def dump(index, default=0, *args, **kw):
print('打印函数参数')
print('---')
print('index:', index)
print('default:', default)
for i, arg in enumerate(args):
print(f'arg[{i}]:', arg)
for key,value in kw:
print(f'keyword_argument {key}:{value}')
print('')
if __name__=='__main__':
dump(0)
dump(0,2)
dump(0,2,"Hello","World")
dump(0,2,"Hello","World", install='Python', run='Python Program')
```
Python函数的参数十分灵活,例如上面的例子:
* `index`: 按顺序位置指定的参数
* `default=0`: 带有默认值的参数
* `*args`: 0个或多个可选的参数
* `**kw`: 0个或多个关键字参数
查看打印结果可以增加对此的理解,语句 `` 的输出是:
```bash
打印函数参数
---
index: 0
default: 2
arg[0]: Hello
arg[1]: World
keyword_argument install:Python
keyword_argument run:Python Program
```
Python 的函数可以调用别的函数,当调用的是自己本身时,就形成了递归调用。以下是一个待完成的递归调用程序,功能需求是:
* 循环打印"Hello,World!"的每个字符
* 循环5次。
```python
# -*- coding: UTF-8 -*-
def circulate_print(str, count=0):
if count == 5:
return
for char in str:
print(char)
# TODO(You): 请在此完成函数递归调用
if __name__ == '__main__':
str = "Hello,World!"
circulate_print(str)
```
请在下面的选项中,选出<span style="color:red">错误</span> 的递归调用选项。
## 答案
```python
circulate_print(str, count)
```
## 选项
### A
```python
circulate_print(str, count+1)
```
### B
```python
count = count+1
circulate_print(str, count)
```
### C
```python
circulate_print(str, count=count+1)
```
......@@ -8,9 +8,47 @@ def circulate_print(str, count=0):
return
for char in str:
print(char)
circulate_print(str, count+1)
circulate_print(str, count=count+1)
def circulate_print_2(str, index=0, *languages, **language_descriptions):
if index >= len(str) or index >= len(languages):
return
key = str[index]
language = languages[index]
if key in language_descriptions:
desc = language_descriptions[key]
print(f'{key}: {language}, {desc}')
else:
print(f'{key}: {language}')
circulate_print_2(str, index+1, *languages, **language_descriptions)
def dump(index, default=0, *args, **kw):
print('打印函数参数')
print('---')
print('index:', index)
print('default:', default)
for i, arg in enumerate(args):
print(f'arg[{i}]:', arg)
for key, value in kw.items():
print(f'keyword_argument {key}:{value}')
print('')
if __name__ == '__main__':
str = "Hello,World!"
circulate_print(str)
dump(0)
dump(0, 2)
dump(0, 2, "Hello", "World")
dump(0, 2, "Hello", "World", install='Python', run='Python Program')
circulate_print_2(
'ABCDEFGJ',
0,
'ABC', 'BCL', 'C语言', 'Dart', 'Erlang', 'F#', 'Go', 'Julia',
A='ABC语言是在NWO(荷兰科学研究组织)旗下CWI(荷兰国家数学与计算机科学研究中心)的Leo Grurts,Lambert Meertens,Steven Pemberton主导研发一种交互式,结构化高级语言,旨在替代BASIC,Pascal等语言,用于教学及原型软件设计。Python创始人Guido van Rossum于20世纪80年代曾在ABC系统开发中工作了数年。',
J='Julia 是一个面向科学计算的高性能动态高级程序设计语言。其语法与其他科学计算语言相似。在许多情况下拥有能与编译型语言相媲美的性能。Julia 是个灵活的动态语言,适合科学和数值计算,性能可与传统静态类型语言媲美。')
circulate_print("HelloWorld!")
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册