[10.17] Dot product of two vectors

Description

实现一个更加节约空间的存储方法存储两个向量

Solution

  1. 对于减少内存,我们可以记录连续重复的数,非常巧妙的compress算法
  2. 对于点乘,我们需要遍历并
def compress(ls):
    result, current_letter, current_count = [], None, 0
    for l in ls:
        if current_letter is None or l == current_letter:
            current_letter, current_count = l, current_count + 1
        else:
            result.append((current_count, current_letter))
            current_letter, current_count = l, 1
    return result + [(current_count, current_letter)]


def dot_product_compressed(compressed_x, compressed_y):
    def _generator(ls):
        if ls:
            for count, item in ls:
                for _ in range(count):
                    yield item
    res = 0
    for (a,b) in zip(_generator(compressed_x), _generator(compressed_y)):
        res += a*b
    return res
    

你可能感兴趣的:([10.17] Dot product of two vectors)