高级农民
 
- 积分
- 2548
- 学分
- 个
- 大米
- 升
- 人参
- 枚
- 水井
- 尺
- 小麦
- 颗
- 萝卜
- 根
- 小米
- 粒
- UID
- 46476
- 注册时间
- 2011-11-5
- 最后登录
- 1970-1-1
- 在线时间
- 小时
- 好友
- 收听
- 听众
- 日志
- 相册
- 帖子
- 主题
- 分享
- 精华
|
# This is for cs61a discussion 5
def square_elements(lst):
"""
2.1.1
Squares every element in lst.
>>> lst = [1, 2, 3]
>>> square_elements(lst)
>>> lst
[1, 4, 9]
"""
for i in range(len(lst)):
lst[i] = lst[i] ** 2
def reverse_list(lst):
"""
2.1.2
Reverses lst in-place (mutating the original list).
>>> lst = [1, 2, 3, 4]
>>> reverse_list(lst)
>>> lst
[4, 3, 2, 1]
>>> pi = [3, 1, 4, 1, 5]
>>> reverse_list(pi)
>>> pi
[5, 1, 4, 1, 3]
"""
for i in range(len(lst) // 2):
lst[i], lst[len(lst)-i-1] = lst[len(lst)-i-1], lst[i]
def add_this_many(x, y, lst):
"""
2.2.1
Adds y to the end of lst the number of times x occurs.
>>> lst = [1, 2, 4, 2, 1]
>>> add_this_many(1, 5, lst)
>>> lst
[1, 2, 4, 2, 1, 5, 5]
"""
count = 0
for ele in lst:
if ele == x:
count += 1
while count > 0:
lst.append(y)
count -= 1
def remove_all(el, lst):
"""
2.2.2
Removes all instances of el from lst.
>>> x = [3, 1, 2, 1, 5, 1, 1, 7]
>>> remove_all(1, x)
>>> x
[3, 2, 5, 7]
"""
while el in lst:
lst.remove(el)
def replace_all(d, x, y):
"""
3.3.1
>>> d = {’foo’: 2, ’bar’: 3, ’garply’: 3, ’xyzzy’: 99}
>>> replace_all(d, 3, ’poof’)
>>> d
{’foo’: 2, ’bar’: ’poof’, ’garply’: ’poof’, ’xyzzy’: 99}
"""
for key in d:
if d[key] == x:
d[key] = y
def replace_all_deep(d, x, y):
"""
3.4.1
>>> d = {1: {2: 3, 3: 4}, 2: {4: 4, 5: 3}}
>>> replace_all_deep(d, 3, 1)
>>> d
{1: {2: 1, 3: 4}, 2: {4: 4, 5: 1}}
"""
for key in d:
if d[key] == x:
d[key] = y
elif type(d[key]) == dict:
replace_all_deep(d[key], x, y)
def remove_all(d, x):
"""
3.4.2
>>> d = {1:2, 2:3, 3:2, 4:3}
>>> remove_all(d, 2)
>>> d
{2: 3, 4: 3}
"""
for key in d:
if d[key] == x:
del d[key] |
评分
-
1
查看全部评分
-
|