一、稠密向量形式的完整代码
稠密向量是指所有元素都有具体数值的向量,它可以用一维数组来表示。下面是稠密向量形式的完整代码:
```python
class DenseVector:
def __init__(self, values):
self.values = values
def add(self, other):
result = []
for i in range(len(self.values)):
result.append(self.values[i] + other.values[i])
return result
def dotProduct(self, other):
result = 0
for i in range(len(self.values)):
result += self.values[i] * other.values[i]
return result
```
二、稀疏向量形式1的完整代码
稀疏向量形式1是指使用字典来表示向量,其中键是非零元素的索引,值是非零元素的数值。下面是稀疏向量形式1的完整代码:
```python
class SparseVector1:
def __init__(self, values):
self.values = values
def add(self, other):
result = {}哪种正则化方式具有稀疏性
for i in self.values:
if i in other.values:
result[i] = self.values[i] + other.values[i]
else:
result[i] = self.values[i]
for i in other.values:
if i not in result:
result[i] = other.values[i]
return result
def dotProduct(self, other):
result = 0
for i in self.values:
if i in other.values:
result += self.values[i] * other.values[i]
return result
```
三、稀疏向量形式2的完整代码
稀疏向量形式2是指使用链表来表示非零元素的索引和数值。下面是稀疏向量形式2的完整代码:
```python
class Node:
def __init__(self, index, value):
self.index = index
self.value = value
= None
class SparseVector2:
def __init__(self, values):
self.head = None
for i in values:
node = Node(i, values[i])
if self.head is None:
self.head = node
else:
current = self.head
is not None:
current =
= node
def add(self, other):
result = SparseVector2({})
current1 = self.head
current2 = other.head
while current1 is not None and current2 is not None:
if current1.index == current2.index:
result.addNode(current1.index, current1.value + current2.value)
current1 =
current2 =
elif current1.index < current2.index:
result.addNode(current1.index, current1.value)
current1 =
else:
result.addNode(current2.index, current2.value)
current2 =
while current1 is not None:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论