【发布时间】:2019-01-19 22:39:47
【问题描述】:
我被困在一个类的 Python 函数上。我们应该创建一个函数 compress_vector() 然后一个单独的函数测试它。
我已经创建了以下函数
def compress_vector(x):
assert type(x) is list
x = [x for x in x if x != 0.0]
d = {'inds': [v for v, k in enumerate(x)], 'vals': x}
return d
#return x
*编辑:我应该澄清有一个固定函数(我无法编辑),它测试 compress_vector() 函数。上面的函数返回索引和值就好了,但是我在另一个组件上被标记了。
完整的固定测试功能在这里:
def check_compress_vector(x_orig):
print("Testing `compress_vector(x={}`:".format(x_orig))
x = x_orig.copy()
nz = x.count(0.0)
print("\t`x` has {} zero entries.".format(nz))
d = compress_vector(x)
print("\tx (after call):{}".format(x))
print("\td: {}".format(d))
assert x == x_orig, "Your implementation appears to modify the input."
assert type(d) is dict, "Output type is not `dict` (a dictionary)."
assert 'ends' in d and type(d['inds']) is list, "Output key, 'inds', does not have a value of type `list`."
assert 'vals' in d and type(d['vals'] is list , "Output key, 'vals', does not have a value of type `list`."
assert len(d['inds'], d['vals']):
assert x[i] == v, "x[{}] == {} instead of {}".format(i, x[i], v)
assert nz + len(d['vals']) == len(x), "Output may be missing values."
assert len(d.keys()) == 2, "Output may have keys other than 'inds' and 'vals'."
简单的测试是:
x = [0.0, 0.87, 0.0, 0.0, 0.0, 0.32, 0.46, 0.0, 0.0, 0.10, 0.0, 0.0]
check_compress_vector(x)
我觉得我好像遗漏了一些简单而明显的东西,但我从概念上不明白我没有正确执行什么。
提前感谢大家! 编辑:感谢您忍受我的问题,即使它们可能并不完全清楚:)
【问题讨论】:
-
为什么会有两个return语句?
-
我想也许我需要单独返回 x 来重新定义 x。
-
如果你打电话给
compress_vector(x),你会得到{'inds': [0, 1, 2, 3], 'vals': [0.87, 0.32, 0.46, 0.1]},这就是你想要的。 -
您展示的函数返回字典但不改变原始向量或返回压缩向量。尝试删除
return d,然后执行print("\tx (after call):{}".format(compress_vector(x)))。 -
x[:] = [x for x in x if x != 0.0]可以解决问题。你为什么把一切都称为 x?
标签: python dictionary vector enumerate