提交 13537fb9 编写于 作者: F feilong

更新第2章

上级 cf392820
......@@ -6,3 +6,4 @@ __pycache__
*.zip
*.out
*.pdf
test.py
\ No newline at end of file
{
"one_line": {
"random.randint": [
"random.rand"
],
"continue": [
"break"
],
"if n == v": [
"if n != v"
],
"elif n < v": [
"elif n > v"
],
"elif n > v": [
"elif n < v"
],
"input": [
"scanf",
"readline"
]
},
"source": "input.py",
"source": "input.md",
"depends": [],
"exercise_id": 91,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 基本输入
心里想一个0-100之间的数字,让用户猜,如果小了或者大了,就给予提示,直到用户猜到
```python
import random
def gauss_num():
v = random.randint(0, 100)
# TODO(You): 请正确实现猜数字逻辑
if __name__ == '__main__':
gauss_num()
```
请选出下列能**正确**实现这一功能的选项。
## template
```python
import random
def gauss_num():
v = random.randint(0, 100)
while True:
n = input("请输入0-100之间的一个数字:")
try:
n = int(n)
except:
print("无效的数字")
continue
if n == v:
print("你猜对了!")
break
elif n < v:
print("你猜错了,我想到的数字比{}大".format(n))
elif n > v:
print("你猜错了,我想到的数字比{}小".format(n))
if __name__ == '__main__':
gauss_num()
```
## 答案
```python
while True:
n = input("请输入0-100之间的一个数字:")
try:
n = int(n)
except:
print("无效的数字")
continue
if n == v:
print("你猜对了!")
break
elif n < v:
print("你猜错了,我想到的数字比{}大".format(n))
elif n > v:
print("你猜错了,我想到的数字比{}小".format(n))
```
## 选项
### A
```python
while True:
n = input("请输入0-100之间的一个数字:")
if n == v:
print("你猜对了!")
break
elif n < v:
print("你猜错了,我想到的数字比{}大".format(n))
elif n > v:
print("你猜错了,我想到的数字比{}小".format(n))
```
### B
```python
while True:
n = read("请输入0-100之间的一个数字:")
if n == str(v):
print("你猜对了!")
break
elif str(n) < str(v):
print("你猜错了,我想到的数字比{}大".format(n))
elif str(n) > str(v):
print("你猜错了,我想到的数字比{}小".format(n))
```
### C
```python
while True:
n = read("请输入0-100之间的一个数字:")
try:
n = int(n)
except:
print("无效的数字")
continue
if n == v:
print("你猜对了!")
break
elif n < v:
print("你猜错了,我想到的数字比{}大".format(n))
elif n > v:
print("你猜错了,我想到的数字比{}小".format(n))
```
{
"one_line": {
"abs(-1) == 1": [
"abs(-1) != 1"
],
"max(10, 100) == 100": [
"max(10, 100) == 10"
],
"min(10, 100) == 10": [
"min(10, 100) == 100"
],
"round(3.5) == 3": [
"round(3.5) == 4"
],
"pow(2, 4) == 16": [
"pow(2, 4) == 8"
],
"all([True, True]) == True": [
"all([True, False]) == True"
],
"any([True, False]) == True": [
"any([True, True]) == True"
],
"bin(2) == '0b10'": [
"bin(2) == '0b00'"
],
"bool({}) == False": [
"bool({}) == True"
],
"bytes([0, 1]) == b'\\x00\\x01'": [
"bytes([0, 1]) == b'\\x01\\x01'"
],
"str(1) == '1'": [
"str(1) == 1"
],
"callable(abs) == True": [
"callable(abs) == False"
],
"chr(97) == 'a'": [
"chr(97) == 'b'"
],
"'count' in dir([])": [
"'count' not in dir([])"
],
"float(1) == 1.0": [
"float(1) == 1.01"
],
"'a, b, c'": [
"'a.b.c'"
],
"hash(chr(97))": [
"hash(chr(98))"
],
"'0x1'": [
"'0x0'"
],
"type({}) ==": [
"type([]) =="
]
},
"source": "util_builtin_01.py",
"source": "util_builtin_01.md",
"depends": [],
"exercise_id": 230,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 常用内置方法(1)
内置函数基本用例,基本测试+执行,请选出以下**会抛出断言异常**的代码。
## template
```python
if __name__ == '__main__':
assert abs(-1) == 1
assert max(10, 100) == 100
assert min(10, 100) == 10
assert round(3.5) == 3
assert pow(2, 4) == 16
assert all([True, True]) == True
assert any([True, False]) == True
assert ascii('你') == "'\\u4f60'"
assert bin(2) == '0b10'
assert bool({}) == False
assert bytes([0, 1]) == b'\x00\x01'
assert str(1) == '1'
assert callable(abs) == True
assert chr(97) == 'a'
assert 'count' in dir([])
assert float(1) == 1.0
assert '{}, {}, {}'.format('a', 'b', 'c') == 'a, b, c'
assert hash("a") == hash(chr(97))
assert hex(1) == '0x1'
assert type({}) == type({'a': 1})
```
## 答案
```python
assert ascii('你') == "'\\u4f60'"
assert bin(2) == '0b10'
assert bytes([0, 1]) == b'01'
assert str(1) == 1
assert chr(97) == 'a'
assert '{}, {}, {}'.format('a', 'b', 'c') == 'a, b, c'
assert hex(1) == '0x1'
```
## 选项
### A
```python
assert abs(-1) == 1
assert max(10, 100) == 100
assert min(10, 100) == 10
assert round(3.5) == 3
assert pow(2, 4) == 16
assert float(1) == 1.0
```
### B
```python
assert all([True, True]) == True
assert any([True, False]) == True
assert bool({}) == False
assert callable(abs) == True
```
### C
```python
assert 'count' in dir([])
assert hash("a") == hash(chr(97))
assert type({}) == type({'a': 1})
```
{
"one_line": {
"assert index == [0, 1, 2]": [
"assert index == [1, 2, 3]"
],
"assert sum([1, -1, 3] == 3)": [
"assert sum([1, -1, 3] == 5)"
],
"(1, 4), (2, 5), (3, 6)": [
"1, 4, 2, 5, 3, 6"
],
"assert len(seasons) == 4": [
"assert seasons.length == 4"
],
"assert shortcut == ['S', 'S', 'F', 'W']": [
"assert shortcut == ['S', 'F', 'W']"
],
"len(non_s_seasons) == 2": [
"len(non_s_seasons) == 3"
],
"assert len(s_seasons) == 2": [
"assert len(s_seasons) == 1"
]
},
"source": "util_builtin_02.py",
"source": "util_builtin_02.md",
"depends": [],
"exercise_id": 236,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 常用内置方法(2)
列表相关内置函数基本用例,基本测试+执行,请选出**每个 assert 结果都是 True**的代码
## template
```python
if __name__ == '__main__':
index = []
for i in range(0, 3):
index.append(i)
assert index == [0, 1, 2]
assert sum([1, -1, 3] == 3)
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
assert list(zipped) == [(1, 4), (2, 5), (3, 6)]
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
assert len(seasons) == 4
shortcut = list(map(lambda s: s[0], seasons))
assert shortcut == ['S', 'S', 'F', 'W']
non_s_seasons = filter(lambda s: s[0] == 'S', seasons)
assert len(non_s_seasons) == 2
s_seasons = list(filter(lambda s: s[0] == 'S', seasons))
assert len(s_seasons) == 2
```
## 答案
```python
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
assert len(seasons) == 4
shortcut = list(map(lambda s: s[0], seasons))
assert shortcut == ['S', 'S', 'F', 'W']
```
## 选项
### A
```python
index = []
for i in range(0, 3):
index.append(i)
assert index == [0, 1, 2]
assert sum([1, -1, 3] == 5)
```
### B
```python
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
assert list(zipped) == [1, 4, 2, 5, 3, 6]
```
### C
```python
seasons = ['Spring', 'Summer', 'Fall', 'Winter', 'sunshine']
non_s_seasons = list(filter(lambda s: s[0] != 'S', seasons))
assert len(non_s_seasons) == 3
s_seasons = list(filter(lambda s: s.lower()[0] == 'S', seasons))
assert len(s_seasons) == 2
```
{
"author": "huanhuilong",
"source": "hash_key_value_set.py",
"source": "hash_key_value_set.md",
"depends": [
"key_value_set.py"
],
......
{
"author": "huanhuilong",
"source": "hash_key_value_set_by_compose.py",
"source": "hash_key_value_set_by_compose.md",
"depends": [
"key_value_set.py"
],
......
{
"source": "calc.py",
"source": "calc.md",
"depends": [],
"exercise_id": 76,
"type": "code_options",
"notebook_enable": true,
"author": "feilong"
"author": "huanhuilong"
}
\ No newline at end of file
# Python 顺序语句
一行一个语句,计算长方形面积
```python
def test():
print("* 如果想计算一个长方形的面积")
print("* 那就先定义长宽,例如:x = 10, y=20")
print("* 紧接着,我们计算长方形的面积:s = x * y")
# TODO(You): 请正确实现计算代码
print("* 现在可以输出结果了,该长方形的面积是:{}".format(s))
if __name__ == '__main__':
test()
```
请选出下列能**正确**实现这一功能的选项。
## template
```python
def test():
print("* 如果想计算一个长方形的面积")
print("* 那就先定义长宽,例如:x = 10, y=20")
print("* 紧接着,我们计算长方形的面积:s = x * y")
x = 10
y = 20
s = x * y
print("* 现在可以输出结果了,该长方形的面积是:{}".format(s))
if __name__ == '__main__':
test()
```
## 答案
```python
x = 10
y = 20
s = x * y
```
## 选项
### A
```python
x = 10
s = x * y
y = 20
```
### B
```python
s = x * y
x = 10
y = 20
```
### C
```python
y = 20
s = x * y
x = 10
```
{
"one_line": {
"ret ==": [
"ret !=",
"ret >=",
"ret <="
],
"\"{}\".format(test)": [
"test"
],
"if ret == ": [
"if int(ret) == "
]
},
"source": "if-else.py",
"source": "if-else.md",
"depends": [],
"exercise_id": 97,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 条件和分支(1)
编写一个程序,能正确提示用户输入测试数字,判断是否是除以2等于5的数字。
```python
def test():
test = 10
ret = input("有一个数除以2是5,请问它是什么?:")
# TODO(You): 请正确实现分支判断并打印的代码
if __name__ == '__main__':
test()
```
请选出以下分支判断打印**不正确**的代码
## template
```python
def test():
test = 10
ret = input("有一个数除以2是5,请问它是什么?:")
if ret == "{}".format(test):
print("恭喜你答对了!")
else:
print("哎,这么简单都答不对,回去重修吧!")
if __name__ == '__main__':
test()
```
## 答案
```python
if ret == "{}".format(test):
print("哎,这么简单都答不对,回去重修吧!")
else:
print("恭喜你答对了!")
```
## 选项
### A
```python
if ret != "{}".format(test):
print("哎,这么简单都答不对,回去重修吧!")
else:
print("恭喜你答对了!")
```
### B
```python
info = "恭喜你答对了!"
if ret != "{}".format(test):
info = "哎,这么简单都答不对,回去重修吧!"
print(info)
```
### C
```python
if ret == "{}".format(test):
print("恭喜你答对了!")
else:
print("哎,这么简单都答不对,回去重修吧!")
```
{
"one_line": {
"is None": [
"is not None",
"not is None",
"None"
]
},
"source": "none.py",
"source": "none.md",
"depends": [],
"exercise_id": 96,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 条件和分支(2)
存在还是不存在,提示用户输入查询关键字,判断是否在字典的key中,输出查询结果。
```python
def is_existed():
database = {
"monkey": "猴王说,我写的程序在五指山上的服务器上运行5000年了!"
}
key = input('请输入你要查询的关键字:')
print("* 猴王数据库正在努力检索中...")
# TODO(You): 请在此实现正确的查询判断
if __name__ == '__main__':
is_existed()
```
请选出下列能**正确**实现这一功能的选项。
## template
```python
def is_existed():
database = {
"monkey": "猴王说,我写的程序在五指山上的服务器上运行5000年了!"
}
key = input('请输入你要查询的关键字:')
print("* 猴王数据库正在努力检索中...")
if database.get(key) is None:
print("* 无法检索到该信息!")
else:
print("* 返回:{}".format(database[key]))
if __name__ == '__main__':
is_existed()
```
## 答案
```python
if database.get(key) is None:
print("* 无法检索到该信息!")
else:
print("* 返回:{}".format(database[key]))
```
## 选项
### A
```python
if database.get(key):
print("* 无法检索到该信息!")
else:
print("* 返回:{}".format(database[key]))
```
### B
```python
if not database[key]:
print("* 返回:{}".format(database[key]))
else:
print("* 无法检索到该信息!")
```
### C
```python
if database.get(key) is None:
print("* 返回:{}".format(database[key]))
else:
print("* 无法检索到该信息!")
```
{
"multiline": [
{
"for item in list:": "for item in list"
},
{
"i = 0": "",
"for item in list:": "for i, item in list:"
},
{
"for item in list:": "for(item in list):"
}
],
"source": "for.py",
"source": "for.md",
"depends": [],
"exercise_id": 78,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 循环1
使用 for 遍历打印列表信息
```python
if __name__ == '__main__':
list = [
{
"id": 966024429,
"number": 2341,
"title": "Question about license.",
"body": "I would like to create a [winget](https://github.com/microsoft/winget-cli) package for jq. 🙏🏻"
},
{
"id": 962477084,
"number": 2340,
"title": "visibility of wiki pages",
"body": "The visibility of wiki pages to search engines is generally limited; for example, the search result for \"jq Cookbook\" looks like this:"
}
]
# TODO(You): 请在此实现遍历打印代码
```
请选出实现**不正确**的代码。
## template
```python
def test(list):
i = 0
for item in list:
print('')
print("## 第{}条信息".format(i))
print("* id: {}".format(item['id']))
print("* number: {}".format(item['number']))
print("* title: {}".format(item['title']))
print("* body: {}".format(item['body']))
i += 1
if __name__ == '__main__':
list = [
{
"id": 966024429,
"number": 2341,
"title": "Question about license.",
"body": "I would like to create a [winget](https://github.com/microsoft/winget-cli) package for jq. 🙏🏻"
},
{
"id": 962477084,
"number": 2340,
"title": "visibility of wiki pages",
"body": "The visibility of wiki pages to search engines is generally limited; for example, the search result for \"jq Cookbook\" looks like this:"
}
]
test(list)
```
## 答案
```python
for i, item in list:
print('')
print("## 第{}条信息".format(i))
print("* id: {}".format(item['id']))
print("* number: {}".format(item['number']))
print("* title: {}".format(item['title']))
print("* body: {}".format(item['body']))
```
## 选项
### A
```python
i = 0
for item in list:
print('')
print("## 第{}条信息".format(i))
print("* id: {}".format(item['id']))
print("* number: {}".format(item['number']))
print("* title: {}".format(item['title']))
print("* body: {}".format(item['body']))
i += 1
```
### B
```python
for i, item in enumerate(list):
print('')
print("## 第{}条信息".format(i))
print("* id: {}".format(item['id']))
print("* number: {}".format(item['number']))
print("* title: {}".format(item['title']))
print("* body: {}".format(item['body']))
```
### C
```python
for i in range(len(list)):
item = list[i]
print('')
print("## 第{}条信息".format(i))
print("* id: {}".format(item['id']))
print("* number: {}".format(item['number']))
print("* title: {}".format(item['title']))
print("* body: {}".format(item['body']))
```
{
"multiline": [
{
"while i < len(list):": "while(i < len(list)):"
},
{
"while i < len(list):": "while i in range(0,len(list):"
},
{
"while i < len(list):": "while i < len(list)"
}
],
"source": "while.py",
"source": "while.md",
"depends": [],
"exercise_id": 77,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 循环1
使用 while 遍历,打印列表信息
```python
if __name__ == '__main__':
list = [
{
"id": 955350543,
"number": 2337,
"title": "Release 1.6 does not have pre-autoreconf'ed configure script",
"body": "If you have a usage question, please ask us on either Stack Overflow (https://stackoverflow.com/questions/tagged/jq) or in the #jq channel (http://irc.lc/freenode/%23jq/) on Freenode (https://webchat.freenode.net/)."
},
{
"id": 954792209,
"number": 2336,
"title": "Fix typo",
"body": ""
}
]
# TODO(You): 请在此实现while循环遍历打印代码
```
请选出下列**实现不正确**的代码。
## template
```python
def test(list):
i = 0
while i < len(list):
item = list[i]
print('')
print("## 第{}条信息".format(i))
print("* id: {}".format(item['id']))
print("* number: {}".format(item['number']))
print("* title: {}".format(item['title']))
print("* body: {}".format(item['body']))
i += 1
if __name__ == '__main__':
list = [
{
"id": 955350543,
"number": 2337,
"title": "Release 1.6 does not have pre-autoreconf'ed configure script",
"body": "If you have a usage question, please ask us on either Stack Overflow (https://stackoverflow.com/questions/tagged/jq) or in the #jq channel (http://irc.lc/freenode/%23jq/) on Freenode (https://webchat.freenode.net/)."
},
{
"id": 954792209,
"number": 2336,
"title": "Fix typo",
"body": ""
}
]
test(list)
```
## 答案
```python
while i in list:
item = list[i]
print('')
print("## 第{}条信息".format(i))
print("* id: {}".format(item['id']))
print("* number: {}".format(item['number']))
print("* title: {}".format(item['title']))
print("* body: {}".format(item['body']))
```
## 选项
### A
```python
i = 0
while i < len(list):
item = list[i]
print('')
print("## 第{}条信息".format(i))
print("* id: {}".format(item['id']))
print("* number: {}".format(item['number']))
print("* title: {}".format(item['title']))
print("* body: {}".format(item['body']))
i += 1
```
### B
```python
i = 0
while True:
item = list[i]
print('')
print("## 第{}条信息".format(i))
print("* id: {}".format(item['id']))
print("* number: {}".format(item['number']))
print("* title: {}".format(item['title']))
print("* body: {}".format(item['body']))
i += 1
if i==len(list):
break
```
### C
```python
it = iter(list)
item = next(it, -1)
i = 0
while item != -1:
print('')
print("## 第{}条信息".format(i))
print("* id: {}".format(item['id']))
print("* number: {}".format(item['number']))
print("* title: {}".format(item['title']))
print("* body: {}".format(item['body']))
item = next(it, -1)
i += 1
```
{
"one_line": {
"map.get('tags')": [
"map.get('profile')"
],
"map['no'] = 10000": [
"map.set('no', 10000)"
],
"dict = {}": [
"dict = new dict{}"
]
},
"source": "dict.py",
"source": "dict.md",
"depends": [],
"exercise_id": 81,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 字典
字典的基本使用,插入key-value,并打印结果
```python
if __name__ == '__main__':
map = {}
map['name'] = "monkey"
map['age'] = 25
map['tags'] = "猴子"
map['tags'] = ['程序员', '户外达人']
map['profile'] = {'info1': "test", "info2": "test"}
print(map['tags'])
print(map['profile'].get("info3"))
```
上述代码的打印结果是?
## template
```python
if __name__ == '__main__':
map = {}
print('* 初始化字典:', map)
print('* 使用下标插入数据到字典')
map['name'] = "monkey"
map['age'] = 25
map['no'] = 10000
for key in map:
value = map[key]
print("{}:{}".format(key, value))
print('* 字典里可以插入其他数据类型,例如插入列表')
map['tags'] = ['程序员', '户外达人']
print('* 打印 tags :{}', map.get('tags'))
print('* 字典里可以插入其他数据类型,例如插入字典')
map['profile'] = {'info1': "test", "info2": "test"}
print('* 打印 profile :{', map.get('profile'))
```
## 答案
```python
['程序员', '户外达人']
None
```
## 选项
### A
```python
猴子
None
```
### B
```python
猴子
test
```
### C
```python
['程序员', '户外达人']
test
```
{
"one_line": {
"array.append": [
"array.push"
],
"array.pop(0)": [
"array.pop()"
],
"array = []": [
"array = new list()"
]
},
"source": "list.py",
"source": "list.md",
"depends": [],
"exercise_id": 80,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 列表
列表的基本使用,使用append/pop,打印结果
```python
if __name__ == '__main__':
array = []
array.append(10)
array.append(20)
array.pop(0)
array.append(30)
array.append(40)
array.pop(0)
print(item)
```
上述代码的打印结果是?
## template
```python
if __name__ == '__main__':
array = []
print('* 初始化列表 array:', array)
print('* 使用 append 追加数据到列表')
array.append(10)
array.append(20)
array.append(30)
array.append(40)
print('* 现在列表的值 array:', array)
print('* 使用 pop 弹出先插入的数据')
array.pop(0)
array.pop(0)
print('* 现在列表的值 array:', array)
print("* 开始遍历列表")
print(item)
```
## 答案
```python
[30, 40]
```
## 选项
### A
```python
[10, 30]
```
### B
```python
[20, 40]
```
### C
```python
[10, 20]
```
{
"one_line": {
"\"双引号字符串里的单引号: 'hello world!'\"": [
"\"双引号字符串里的单引号: \"hello world!\"\""
],
"'单引号字符串里的双引号: \"hello world!\"'": [
"'单引号字符串里的双引号: 'hello world!''"
],
"* \"双引号\" ": [
"* '''双引号''' "
],
"* '单引号'": [
"* '''单引号'''"
],
"\"字符串加法\"+\"字符串加法\"": [
"\"字符串加法\"*\"字符串加法\""
],
"\"字符串乘法\"*3": [
"\"字符串乘法\"+3"
]
},
"source": "string.py",
"source": "string.md",
"depends": [],
"exercise_id": 82,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 字符串
使用字符串,几种不同引号的混合使用,请选出下列字符串使用错误的代码。
## template
```python
def test():
print("双引号字符串")
print('单引号字符串')
print("双引号字符串里的单引号: 'hello world!'")
print('单引号字符串里的双引号: "hello world!"')
triple = '''
三引号字符串
'''
print(triple)
triple2 = '''
三引号字符串的便利:
* "双引号"
* '单引号'
'''
print(triple2)
print("字符串加法"+"字符串加法")
print("字符串乘法"*3)
print(",".join(["字符串数组的聚合", "字符串数组的聚合", "字符串数组的聚合"]))
if __name__ == '__main__':
test()
```
## 答案
```python
print("双引号字符串里的双引号: "hello world!"")
print('单引号字符串里的单引号: 'hello world!'')
triple2 = '''
三引号字符串里的三引号:
* "双引号"
* '单引号'
* '''三引号'''
'''
```
## 选项
### A
```python
print("双引号字符串")
print('单引号字符串')
triple = '''
三引号字符串
'''
```
### B
```python
print("双引号字符串里的单引号: 'hello world!'")
print('单引号字符串里的双引号: "hello world!"')
```
### C
```python
print("字符串加法"+"字符串加法")
print("字符串乘法"*3)
print(",".join(["字符串数组的聚合", "字符串数组的聚合", "字符串数组的聚合"]))
```
{
"one_line": {
"('红色',)": [
"('红色')"
],
"('红色', '绿色', '蓝色')": [
"('红色', ('绿色',), '蓝色')"
],
"0.6, 0.8, 0.3": [
"0.6, (0.8, 0.3)"
]
},
"source": "tuple.py",
"source": "tuple.md",
"depends": [],
"exercise_id": 79,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 元组
<img src="https://img-mid.csdnimg.cn/release/static/image/mid/ask/321539019236199.jpg?x-oss-process=image/auto-orient,1/resize,w_320,m_lfit"/>
请选出下列元组**使用错误**的代码。
## template
```python
import math
if __name__ == '__main__':
tuple1 = ('红色',)
for element in tuple1:
print(element)
tuple = ('红色', '绿色', '蓝色')
for element in tuple:
print(element)
print("不带括号的也是元组:")
r, g, b = 0.6, 0.8, 0.3
print("普通颜色[0-1]:({}, {}, {})".format(r, g, b))
hr, hg, hb = (math.pow(r, 3/2), math.pow(g, 4/5), math.pow(b, 3/2))
print("使用《黑客帝国》绿色滤镜算法计算后的颜色[0-1]:({}, {}, {})".format(hr, hg, hb))
```
## 答案
```python
tuple1 = ('红色')
for element in tuple1:
print(element)
```
## 选项
### A
```python
tuple = ('红色', '绿色', '蓝色')
for element in tuple:
print(element)
```
### B
```python
print("不带括号的也是元组:")
r, g, b = 0.6, 0.8, 0.3
print("普通颜色[0-1]:({}, {}, {})".format(r, g, b))
```
### C
```python
r, g, b = 0.6, 0.8, 0.3
hr, hg, hb = (math.pow(r, 3/2), math.pow(g, 4/5), math.pow(b, 3/2))
print("使用《黑客帝国》绿色滤镜算法计算后的颜色[0-1]:({}, {}, {})".format(hr, hg, hb))
```
{
"one_line": {
"list(set(lista))": [
"list(lista)",
"set(lista)"
],
"item >= bound": [
"item > bound"
],
"res = []": [
"res = {}"
]
},
"source": "builtin_class.py",
"source": "builtin_class.md",
"depends": [],
"exercise_id": 240,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 内置类型
内置类的使用,列表元素去重+过滤小于3的元素
```python
def remove_duplicates(items):
# TODO(You): 实现去重
def filter_element(items, bound):
# TODO(You): 实现过滤
if __name__ == '__main__':
a = [1, 2, 3, 4, 4, 5, 5]
print('输入: {}'.format(a))
res = remove_duplicates(a)
print('去重后的结果:{}'.format(res))
bound = 3
res = filter_element(a, bound)
print('过滤小于{}的元素:{}'.format(bound, res))
```
请选出以下对`remove_duplicates``filter_element` **实现错误**的代码。
## template
```python
def remove_duplicates(items):
res = list(set(items))
return res
def filter_element(items, bound):
res = []
for item in items:
if item >= bound:
res.append(item)
return res
if __name__ == '__main__':
a = [1, 2, 3, 4, 4, 5, 5]
print('输入: {}'.format(a))
res = remove_duplicates(a)
print('去重后的结果:{}'.format(res))
bound = 3
res = filter_element(a, bound)
print('过滤小于{}的元素:{}'.format(bound, res))
```
## 答案
```python
def filter_element(items, bound):
res = [item for item in items if item < bound]
return res
```
## 选项
### A
```python
def remove_duplicates(items):
res = list(set(items))
return res
```
### B
```python
def remove_duplicates(items):
res = []
for item in items:
if not item in res:
res.append(item)
return res
```
### C
```python
def filter_element(items, bound):
res = []
for item in items:
if item >= bound:
res.append(item)
return res
```
......@@ -3,7 +3,6 @@
使用嵌套的三元组表达式统计数字频率,如果是2的倍数加1,如果是4的倍数加2,否则加0
```python
if __name__ == '__main__':
pi = [3, 14, 15, 9, 26, 5, 35, 8, 97, 932]
even_count = 0
......
......@@ -3,7 +3,6 @@
所谓断言,就是证明,使用 assert 对输入函数输入参数和函数返回结果分别做前校验和后校验
```python
def check_param(key_value_map, key):
'''参数校验,断言就是对输入参数的一个证明,这些参数必须符合这些要求
key_value_map: 非空字典
......
......@@ -5,7 +5,6 @@
```python
import time
class TimeSpan:
# TODO(You): 请正确实现计时器的__enter__和__exit成员
......
......@@ -3,14 +3,11 @@
JSON文件读写
```python
import json
def load_json(file):
# TODO(You): 实现加载json文件代码
def dump_json(file, obj):
# TODO(You): 实现将dict写入json文件的代码
......
......@@ -8,17 +8,14 @@ import traceback
import logging
logger = logging.getLogger(__name__)
def load_json(file):
with open(file, 'r') as f:
return json.loads(f.read())
def test():
# TODO(You):
ret = load_json('a.json')
if __name__ == '__main__':
test()
```
......
......@@ -3,7 +3,6 @@
Python 高阶函数编程,使用 lambda 表达式获取key,将list转成dict
```python
def list_to_dict(list, key_func):
d = {}
for item in list:
......@@ -17,7 +16,6 @@ def list_to_dict(list, key_func):
return d
if __name__ == '__main__':
list = [
{"name": "alice", "age": 100},
......
......@@ -7,7 +7,6 @@
## template
```python
if __name__ == '__main__':
with open('/tmp/test.txt', 'w') as f:
f.write("test")
......
......@@ -9,7 +9,6 @@ sys, os, math, time, date
## template
```python
import sys
import os
import math
......
......@@ -9,5 +9,5 @@ if __name__ == '__main__':
# walker = TreeWalker("data", "python", "python")
# walker.walk()
md = MDWalker('data/1.python初阶/3.进阶语法')
md = MDWalker('data/1.python初阶/2.基础语法')
md.walk()
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册